简体   繁体   English

使用 React.js 在 OpenLayers 中叠加

[英]Overlays in OpenLayers with React.js

With React.js 16 and OpenLayers 6.5 I created a component which displays a map with an overlay:使用 React.js 16 和 OpenLayers 6.5,我创建了一个组件,该组件显示带有叠加层的地图:

import React from "react";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import Map from "ol/Map";
import View from "ol/View";
import Overlay from "ol/Overlay";

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.mapRef = React.createRef();
    this.overlayRef = React.createRef();
  }

  componentDidMount() {
    this.map = new Map({
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      target: this.mapRef.current,
      view: new View({
        center: [800000, 5000000],
        zoom: 5,
      }),
    });

    const overlay = new Overlay({
      position: [800000, 5000000],
      element: this.overlayRef.current,
    });
    this.map.addOverlay(overlay);
  }
  render() {
    return (
      <>
        <div ref={this.mapRef} id="map"></div>
        <div ref={this.overlayRef}>Overlay</div>
      </>
    );
  }
}

export default Map;

This code works fine until the component gets unmounted.此代码工作正常,直到组件被卸载。 Then I receive the error然后我收到错误

Uncaught DOMException: Node.removeChild: The node to be removed is not a child of this node

and the app crashes.应用程序崩溃。 I guess it happens because OpenLayers is modifying the DOM structure and thus React gets confused.我猜这是因为 OpenLayers 正在修改 DOM 结构,因此 React 会感到困惑。

Does anybody knows how to add an overlay which does not modify the DOM structure?有人知道如何添加不修改 DOM 结构的叠加层吗? Or any other solution to circumvent the problem?或任何其他解决方案来规避问题?

The problem is that OL Overlay class takes the passed in element this.overlayRef.current and appends it as child to its internal element changing the DOM structure.问题是 OL Overlay类接受传入的元素this.overlayRef.current并将其作为子元素附加到其内部元素,从而改变 DOM 结构。 You can anticipate this and preemptively place your custom overlay element inside Overlay 's internal element using React portal :您可以预见到这一点,并使用React 门户抢先将您的自定义叠加元素放置在Overlay的内部元素中:

ReactDOM.createPortal((<div>Overlay</div>), overlay.element)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM