小编典典

结合React和Leaflet的好方法

reactjs

我正在做一个将React和Leaflet结合起来的项目,但是我必须说我在语义上有些困难。

由于大多数内容都是由Leaflet直接管理的,所以我不知道是否将Leaflet映射实例添加为React组件中的状态是否有意义。

使用Leaflet创建标记时存在相同的问题,因为它不返回任何内容,因此我实际上没有任何要渲染的内容。逻辑本身对我来说似乎很模糊。

这就是我开始做的。它正在工作,但是我感觉我在编写错误的代码并错过了这个概念。

/** @jsx React.DOM */

/* DOING ALL THE REQUIRE */
var Utils = require('../core/utils.js');

var Livemap = React.createClass({
    uid: function() {
        var uid = 0;
        return function(){
            return uid++;
        };
    },
    getInitialState: function() {
        return {
            uid: this.uid()
        }
    },
    componentDidMount: function() {
        var map = L.map('map-' + this.state.uid, {
            minZoom: 2,
            maxZoom: 20,
            layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})],
            attributionControl: false,
        });
        map.fitWorld();
        return this.setState({
            map: map
        });
    },
    render: function() {
        return (
            <div className='map' id={'map-'+this.state.uid}></div>
        );
    }
});

(function(){
    Utils.documentReady(function(){
        React.render(
            <Livemap />,
            document.body
        )
    });
})();

所以我的问题是:

  • 这个样本看起来合法吗?
  • 您将如何处理添加标记和管理标记事件的逻辑?

阅读 388

收藏
2020-07-22

共1个答案

小编典典

  • 您无需自己管理唯一性,即“ UID”。相反,您可以使用getDOMNode访问组件的真实节点。Leaflet的API支持字符串选择器或HTMLElement实例。
  • Leaflet正在管理渲染,因此map不应继续存在state。仅存储state会影响React的DOM元素渲染的数据。

除了这两点,请正常使用Leaflet API,并根据需要将React组件中的回调绑定到Leaflet映射。此时,React只是一个包装器。

import React from 'react';
import ReactDOM from 'react-dom';

class Livemap extends React.Component {

    componentDidMount() {
        var map = this.map = L.map(ReactDOM.findDOMNode(this), {
            minZoom: 2,
            maxZoom: 20,
            layers: [
                L.tileLayer(
                    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                    {attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})
            ],
            attributionControl: false,
        });

        map.on('click', this.onMapClick);
        map.fitWorld();
    }

    componentWillUnmount() {
        this.map.off('click', this.onMapClick);
        this.map = null;
    }

    onMapClick = () => {
        // Do some wonderful map things...
    }

    render() {
        return (
            <div className='map'></div>
        );
    }

}
2020-07-22