我正在使用 React 渲染传单 map 。由于我无法从 DOM 中获取 map 对象实例,我如何从不同路由中的组件中检索实例?
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;
非常感谢
最佳答案
您可以将 Main 中的 map 实例作为属性传递给子组件:
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;
关于javascript - 对象实例的引用 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190360/