反应 OpenLayers 父上下文

React OpenLayers parent context

我也构建了一个可以正常工作的应用程序(此处的小示例:https://jsfiddle.net/mcneela86/nvtss60h/)。

现在我需要将组件分解为更多 manageable/reusable 个组件。目前我有一个 <Map /> 组件,所有逻辑都发生在该组件内。

我想要的是这样的(https://jsfiddle.net/mcneela86/47581h2m/):

<Map>
  <ScaleLine units="imperial" />
  <Layer source={...some-source...} />
</Map>

我 运行 遇到的问题是,在示例中,我需要从子组件访问父组件上的 this.map 以添加比例线。

有没有办法从子组件访问父上下文?

我正在使用 React 16 和 OpenLayers 4。

您可以通过道具将 this.map object 传递给 children。另请注意 componentDidMount 在渲染后执行,因此您可能希望在构造函数中进行初始化。

class Map extends React.Component {
  constructor() {
    super();
       // .........
        // Add map, base view and layer
    this.map = new ol.Map({
      target: 'map',
      layers: [this.baseLayer],
      view: this.baseView
    });

    //......
  }

  render() {
    const { children } = this.props;
    let childrenWithProps = React.Children.map(children, child =>
    React.cloneElement(child, { mapObject: this.map }));

    return (
      <div id="map">
        {childrenWithProps}
      </div>
    );
  }
}

class ScaleLine extends React.Component {
  componentDidMount() {
    // Add scale line - not sure how to add to the parent context
    this.props.mapObject.addControl(new ol.control.ScaleLine({ units: this.props.units }));
  }

  render() {
    return '';
  }
}

好的,我想我明白了。我正在使用上下文,我知道这是实验性的,但我计划在不久的将来将其分解为一个单独的 library/node 模块,因此我对所涉及的风险感到满意。

这是示例应用程序的 fiddle (https://jsfiddle.net/mcneela86/fk250y38/),它也按照我想要的方式运行。我添加了两个 ScaleLine 子组件来帮助说明它是如何工作的。

基本上我已经采纳了 Dane 关于将 this.map 代码移动到构造函数的评论,然后我使用 React 的上下文 API(getChildContext 方法)使 this.map 可用于后代的 before使用 componentDidMount 生命周期方法设置地图显示的目标 DOM 元素。

我还发现这个 (https://www.youtube.com/watch?v=lxq938kqIss) YouTube 视频非常有用,所以感谢 'ReactCasts' 的人。值得观看他们关于 React 上下文的两部分视频系列,以获得上下文的加号和减号的很好解释的示例 API。

我希望这对以后的其他人有所帮助。