[英]Reference on object instance - React
我正在使用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;
非常感謝
您可以將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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.