javascript - 对象实例的引用 - React

标签 javascript reactjs leaflet

我正在使用 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/

相关文章:

javascript - 使用 React Router,我如何为 HTML 元素分配一个类?

reactjs - React限制嵌套更新的数量以防止无限循环

javascript - react : npm command to create a new component?

javascript - 为什么下划线使用 `root` 而不是 `this` ?

javascript - 正确编写 JavaScript 正则表达式来分割字符串

javascript - AngularJs onClick 防止滚动到顶部

javascript - 在reactjs中使用props将值传递给其他组件

javascript - mapbox/leaflet js map 上的粗白线

传单 : how to get the popup content on marker click?

javascript - 找到传递的每一个数据 block ?