我使用react来渲染传单地图。由于我无法从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 :(得分:0)
您可以将Main中的地图实例作为属性传递给子组件:
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>
);
}
});
路线/ 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;