访问父组件变量

Accessing Parent Component Variable

本文关键字:变量 组件 访问      更新时间:2023-09-26

我试图将我的Openlayers应用程序表达为基于组件的应用程序。有一个像<Marker />这样的孩子的<Map />组件,我需要从<Marker />访问我的<Map />组件的this.map属性。

从具象组件中获取此标记:

<Map center={[-1.81185, 52.44314]} zoom={6}>
    <Marker title="This is a marker" coordinate={[-1.81185, 52.44314]} />
</Map>

<Map />组件:

export default class Map extends React.Component {
    static propTypes = {
        center: React.PropTypes.array.isRequired,
        zoom: React.PropTypes.number.isRequired
    }
    constructor(props) {
        super(props);
        this.map = null;
    }

    componentDidMount() {
        this.map = new ol.Map(/* code removed for brevity */);
    }
    renderChildren() {
        const { children } = this.props;
        if (!children) return;
        return React.Children.map(children, c => {
            return React.cloneElement(c, {
                map: this.map
            });
        })
    }
    render() {
        return <div id="map">{this.renderChildren()}</div>
    }
}

<Marker />组件:

export default class Marker extends React.Component {
    static propTypes = {
        map: React.PropTypes.object,
        coordinate: React.PropTypes.array.isRequired,
        title: React.PropTypes.string
    }
    componentDidMount() {
        const { map, coordinate, title } = this.props;
        if (!map) return;
        var marker = createMarkerAndPlaceOn(map);
    }

    render() {
        return null;
    }
}

如您所见,我尝试通过克隆元素并为其提供属性来向下传递 this.map 属性。

但是,由于我需要依赖 DOM 节点#map进行渲染,所以我可以先在 <Map />componentDidMount() 方法中初始化我的new ol.Map()。这意味着我的子组件在渲染时没有获得this.map的实例。

有没有干净的、非反模式的方法来实现这一点?

您可以将

map存储在state中,一旦准备好,它就会传给孩子们。

constructor(props) {
    super(props);
    this.state = {
        map: null
    }
    this.renderChildren = this.renderChildren.bind(this);
 }

componentDidMount() {
    this.setState({map : new ol.Map()});
}
renderChildren() {
    const { children } = this.props;
    if (!children) 
        return;
    if(!this.state.map)
        return <div>Loading markers</div>
    return React.Children.map(children, c => {
        return React.cloneElement(c, {
            map: this.state.map
        });
    })
}

斯菲德尔