我在React组件中有一个OpenLayers(5.3.3)映射。我正在尝试显示标记点击时的弹出窗口。一切正常,直到我需要弹出窗口内的单击处理程序为止。这是代码的相关部分:
class Map extends Component {
constructor(props) {
super(props);
this.state = {
markers: [],
selectedMarker: null
};
}
updateSelectedMarker = id => {
const selectedMarker = this.state.markers.find(marker => marker.id === id);
this.setState({ selectedMarker });
};
openPopover = id => {
this.updateSelectedMarker(id);
const popoverElement = document.getElementById(`popover-${id}`);
const popoverElementClone = popoverElement.cloneNode(true);
popoverElementClone.setAttribute("id", `popover-${id}-clone`);
const popupOverlay = new Overlay({
id: id,
element: popoverElementClone
});
this.olmap.addOverlay(popupOverlay);
};
render() {
return (
<div id="map">
{this.state.selectedMarker !== null && (
<Popover
id={this.state.selectedMarker.id}
/>
)}
</div>
);
}
}
const Popover = ({ id }) => {
const handleClick = () => {
console.log("Do stuff");
};
return (
<div className="popover" id={`popover-${id}`}>
<button className="popover__button" onClick={handleClick}></button>
</div>
);
};
这是当前的工作方式:
否则,一切都会按预期工作,但是克隆的Popover上的onClick处理程序将丢失(它可用于原始Popover元素)。克隆popover元素的原因是,如果移动已渲染的元素(Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
)
应对这种情况的正确方法是什么?谢谢!