지도를 클릭하여지도 상자 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을 따르고 있습니다.
부모 클래스에서 이와 같이 자식 구성 요소를 정의하십시오.
<ChildComponent
parent={this}
/>
그런 다음 자식 클래스에서 부모 클래스 함수를 호출하십시오.
this.props.parent.someFunction();
전체 작동 데모. 이 예에서 자식은 부모의id
필드를표시하지만 함수 호출 일 수도 있으며 함수 호출에서 자식에서 부모 함수로 전달하려는 인수를 포함 할 수 있습니다.
궁금하다면 비슷한 질문에 대한 답변이 있습니다 : Class Component를 사용하여 React에서 Child에서 Parent로 Ref를 전달합니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다