我正试着在我的React中使用传单。我遇到了一个问题。Leaflet.js需要div组件在启动映射时预先存在.React在呈现组件之前不会“创建”div,因此传单会抛出一个错误。无论出于什么原因,getDOMNode()和findDOMNode()都返回“不是函数”。
代码:
import React from 'react';
import {render} from 'react-dom';
import L from 'leaflet';...a稍晚些
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: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
return (
<div id="map">
<h1>hi</h1>
</div>
);这将返回一个错误,即“映射容器未找到”。
谢谢。
发布于 2016-06-06 15:31:25
您可以在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: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
}
render() {
return <div id="map">xx</div>
}
}发布于 2020-08-02 13:30:14
如果您使用的是类组件,那么其他的答案是很棒的。如果您必须将它与功能组件(使用、钩子、)一起使用,则可能需要编写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节点之后,映射将被初始化。
参考资料:反应钩.
发布于 2018-11-14 17:28:34
由于react 16.3,所以有一种新的方法可以轻松地创建引用。
注意:引用可以存储在构造函数中,因为引用可以在创建jsx之前创建。
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>
}
}https://stackoverflow.com/questions/37661136
复制相似问题