反应和传单

React and Leaflet

我正在尝试在我的 React 应用程序中使用 Leaflet。我 运行 遇到了问题。 Leaflet.js 要求 div 组件在启动地图时预先存在。在呈现组件之前,React 不会 "create" div,因此 leaflet 会抛出错误。无论出于何种原因,getDOMNode() 和 findDOMNode() return "not a function"。

代码:

import React from 'react';
import {render} from 'react-dom';
import L from 'leaflet';

...稍后

export default class Mapbox extends React.Component {
  render() {
    var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

    return (

      <div id="map">
    <h1>hi</h1>
    </div>
    );

这 return 是 "Map Container not Found" 的错误。

谢谢。

你可以在里面初始化地图componentDidMount

class Mapbox extends React.Component {
  componentDidMount() {
    this.map();
  }

  map() {
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
  }

  render() {
    return <div id="map">xx</div>  
  }
}

Example

使用"refs"。 Refs 用于 return 对元素的引用。 文档 here

class Map extends React.Component {

  componentDidMount() {
    const node = this.node;
    var map = var map = L.map(node).setView([51.505, -0.09], 13);
  }

  render() {
    return <div ref={(node) => { this.node = node }}></div>
  }
}

自从 react 16.3 以来,有一种新方法可以轻松创建引用。

note:the references can be stored in constructor as the refernces can be created prior to the jsx div is created.

class Map extends React.Component {


  componentDidMount() {
   this.map = React.createRef();
   var map = L.map(this.map).setView([51.505, -0.09], 13);
  }

  render() {
    return <div ref={this.map}></div>
  }
}

如果您使用 class 组件,其他答案也很好。如果您必须将它与功能组件一起使用(使用 Hooks),那么您可能需要编写代码 useRef.

function Map({}) {
  // define the ref here
  const mapRef = useRef(null);

  useEffect( () => {
// set the initialized map to the ref
    mapRef.current = L.map('map').setView([51.505, 3], 13);
    
    }, []);

// pass it in the required div node
  return (
    <div ref={mapRef} id="map" className="p-2">
    </div>
  );

}

这样地图会在 DOM 节点渲染完成后初始化。

参考:React hooks.