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