【问题标题】:How can I pass a mapbox coordinates to a parent class in react?如何在反应中将地图框坐标传递给父类?
【发布时间】:2020-10-10 02:58:39
【问题描述】:

我正在尝试通过单击地图在 mapbox gl 地图上设置标记,然后将 lngLat 对象传递回父组件。请告诉我我该怎么做。我是学习反应的新手,但我知道道具只能从父类继承,而 setState 只能设置本地状态。

   // add a marker when user clicks a point
    map.on("click", "random-points-layer", e => {
      if (e.features.length) {
        const feature = e.features[0];
        document.getElementById('info').innerHTML =
      // e.point is the x, y coordinates of the mousemove event relative
      // to the top-left corner of the map
        JSON.stringify(e.point) +
        '<br />' +
       // e.lngLat is the longitude, latitude geographical position of the event
        JSON.stringify(e.lngLat.wrap());

//----------------------------------------------------------------------------------------------------
//   add a marker to the map
        var marker = new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map);
//----------------------------------------------------------------------------------------------------
      }
    });

父组件长这样

  render() {
     <div>
      <h1>Activate a beacon<h1/>
      <Map/>
     <div/>
}

我正在关注这个教程https://github.com/laneysmith/react-mapbox-example

【问题讨论】:

  • 嗨,约翰!我刚刚回答了一个非常非常相似的问题——Passing a Ref from a Child to a Parent in React with Class Component。这显示了如何使用子组件的引用来共享函数或组件数据/状态,我认为这可能适合您。希望这会有所帮助!
  • 感谢您的帮助。你对另一个问题的回答真的很有帮助
  • 嘿,约翰!优秀!我也在下面更新了我的答案,并提供了另一个问题的链接。别忘了,如果有帮助,您可以将其标记为已接受,以便其他人知道在哪里查找!谢谢!

标签: javascript reactjs mapbox-gl-js


【解决方案1】:

在你的父类中定义你的子组件...

<ChildComponent
    parent={this}
/>

然后在你的子类中调用你的父类函数...

this.props.parent.someFunction();

Full working demo. 在本例中,子级显示父级的 id 字段,但它也可能是一个函数调用,在函数调用中,我可以包含我想要传递的任何参数子到父函数。

如果您好奇,我有一个类似问题的答案:Passing a Ref from a Child to a Parent in React with Class Component

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多