【问题标题】:React OpenLayers parent context反应 OpenLayers 父上下文
【发布时间】:2018-07-17 16:47:40
【问题描述】:

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

现在虽然我需要将组件分解为更易于管理/可重用的组件。目前我有一个<Map /> 组件,所有逻辑都发生在该组件内。

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

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

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

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

我正在使用 React 16 和 OpenLayers 4。

【问题讨论】:

    标签: reactjs openlayers


    【解决方案1】:

    您可以通过道具将this.map 对象传递给孩子。另请注意,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 '';
      }
    }
    

    【讨论】:

    • 感谢您的回复。当我尝试这个解决方案时,我在子组件中得到了 undefined 的 mapObject。
    • 使用this.props.mapObject 访问对象。我已经更新了答案
    • jsfiddle.net/mcneela86/8xrhjt9t this.props.mapObjectundefined
    • 好的,抱歉花了这么多时间。您已经在 componentDidMount 中初始化了 this.map,这在您的渲染之后 被调用,因此它是未定义的。请在构造函数中初始化this.map
    • 再次感谢您的更新,您是正确的,对象在放置在构造函数中时会通过,但在使用此方法时不会呈现到屏幕上。
    【解决方案2】:

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

    这是示例应用程序的小提琴 (https://jsfiddle.net/mcneela86/fk250y38/),它也可以按照我的要求工作。我添加了两个ScaleLine 子组件来帮助说明它是如何工作的。

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

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

    我希望这对将来的其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2017-02-24
      • 2017-04-12
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      相关资源
      最近更新 更多