2015-12-09 73 views
0

我正在使用響應呈現傳單地圖。由於我無法從DOM獲取地圖對象實例,因此如何從不同路線內的組件獲取實例?參考對象實例 - 反應

App.js

const Main = React.createClass({ 

    componentDidMount: function() { 
    map = L.map('map', {}).setView([45, 0], min_zoom); 
    let layer = L.tileLayer('https://api....}', { }).addTo(map); 
    }, 

    render() { 
    return (
     <div id='map'> 
     <div id='container'> 
      {this.props.children} 
     </div> 
     </div> 
    ); 
    } 
}); 

import Travel from './routes/Travel'; 

render((
    <Router history={history}> 
    <Route path="/" component={Main}> 
     <Route path="/travel/:name" component={Travel}/> 
    </Route> 
    </Router> 
), document.getElementById('app')); 

路由/ Travel.js

const Travel = React.createClass({ 

    componentDidMount: function() { 

    GET THE MAP INSTANCE HERE // UNDEFINED 
    }, 


    render() { 
     return (
     <div id='storyBox'> 
     </div> 
    ); 
    }); 

    module.exports = Travel; 

非常感謝

回答

0

你可以在主要通過地圖實例的子組件的屬性:

const Main = React.createClass({ 

    componentDidMount: function() { 
    this.map = L.map('map', {}).setView([45, 0], min_zoom); 
    let layer = L.tileLayer('https://api....}', { }).addTo(map); 
    }, 

    render() { 
    return (
     <div id='map'> 
     <div id='container'> 
      {React.cloneElement(this.props.children, {map: this.map})} 
     </div> 
     </div> 
    ); 
    } 
}); 

路線s/Travel.js

const Travel = React.createClass({ 

    componentDidMount: function() { 
    if (this.props.map) { 
     // whatever 
    } 
    }, 
    render() { 
     if (!this.props.map) return null; 

     return (
     <div id='storyBox'> 
     </div> 
    ); 
    }); 

    module.exports = Travel; 
+0

你讓我的日子傑克。謝謝。 – Yoann