如何将 mapbox 坐标传递给父 class 反应?
How can I pass a mapbox coordinates to a parent class in react?
我正在尝试通过单击地图在 mapbox gl 地图上设置标记,然后将 lngLat 对象传回父组件。请告诉我该怎么做。我是学习反应的新手,但我知道道具只能从父 class 继承,而 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/>
}
在 parent class...
中像这样定义 child 组件
<ChildComponent
parent={this}
/>
然后在 child class...
中调用 parent class 函数
this.props.parent.someFunction();
Full working demo. 在此示例中,child 显示 parent 的 id
字段,但它也可能是一个函数调用,并且在函数调用,我可以包含我想从 child 传递给 parent 函数的任何参数。
我有一个类似问题的答案,如果你好奇的话:。
我正在尝试通过单击地图在 mapbox gl 地图上设置标记,然后将 lngLat 对象传回父组件。请告诉我该怎么做。我是学习反应的新手,但我知道道具只能从父 class 继承,而 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/>
}
在 parent class...
中像这样定义 child 组件<ChildComponent
parent={this}
/>
然后在 child class...
中调用 parent class 函数this.props.parent.someFunction();
Full working demo. 在此示例中,child 显示 parent 的 id
字段,但它也可能是一个函数调用,并且在函数调用,我可以包含我想从 child 传递给 parent 函数的任何参数。
我有一个类似问题的答案,如果你好奇的话: