在React中克隆元素

时间:2019-09-19 13:12:02

标签: javascript reactjs clone openlayers

我在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>
    );
};

这是当前的工作方式:

  1. 点击地图标记会触发openPopover功能
  2. 状态已更新为selectedMarker对象
  3. React使用来自selectedMarker状态的信息在DOM中呈现Popover组件
  4. 将弹出窗口克隆,添加并显示在OpenLayers叠加层中

否则,一切都会按预期工作,但是克隆的Popover上的onClick处理程序将丢失(它可用于原始Popover元素)。克隆popover元素的原因是,如果移动已渲染的元素(Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

,React将会崩溃

应对这种情况的正确方法是什么?谢谢!

0 个答案:

没有答案