react和传单

IT技术 javascript reactjs leaflet mapbox
2021-05-23 20:58:20

我正在尝试在我的 React 应用程序中使用 Leaflet。我遇到了一个问题。Leaflet.js 要求 div 组件在启动地图时预先存在。React 在呈现组件之前不会“创建” div,因此传单会引发错误。无论出于何种原因,getDOMNode() 和 findDOMNode() 都返回“非函数”。

代码:

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>
    );

这将返回“未找到地图容器”的错误。

谢谢。

4个回答

你可以在里面初始化地图 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

如果您使用的是类组件,其他答案也很棒。如果您必须将它与功能组件(使用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

由于 react16.3有一种新方法可以轻松创建引用。

注意:引用可以存储在构造函数中,因为可以在创建 jsx div 之前创建引用。

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>
  }
}

使用“参考”。Refs 用于返回对元素的引用。文档在这里

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>
  }
}