2016-07-18 153 views
1

我想將我的Openlayers應用程序表示爲基於組件的應用程序。有一個<Map />組件與兒童像<Marker />,我需要訪問我的<Map />組件的this.map財產<Marker />訪問父組件變量

從表象成分藉此標記:

<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上呈現,我可以先初始化我new ol.Map()<Map />componentDidMount()方法。這意味着我們的子組件在渲染時沒有得到this.map的實例。

是否有任何干淨的,非反模式的方式來實現這一目標?

回答

2

您可以將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 
     }); 
    }) 
} 

jsfiddle

+0

這正是我一直在尋找,非常感謝! :-) – janhartmann