[英]Reference on object instance - React
I'm using react to render a leaflet map. 我正在使用react渲染传单地图。 Since I can't get the map object instance from the DOM, how can I retrieve the instance from components inside different routes ?
由于无法从DOM获取地图对象实例,因此如何从不同路线内的组件中检索实例?
App.js 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'));
Routes/Travel.js 路线/ Travel.js
const Travel = React.createClass({
componentDidMount: function() {
GET THE MAP INSTANCE HERE // UNDEFINED
},
render() {
return (
<div id='storyBox'>
</div>
);
});
module.exports = Travel;
Many thanks 非常感谢
You could pass the map instance in Main to the child component as a property: 您可以将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>
);
}
});
Routes/Travel.js 路线/ 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.