结合React和Leaflet的好方法

sou*_*uls 32 javascript leaflet reactjs

我正在研究一个将React和Leaflet结合起来的项目,但我必须说我在语义方面遇到了一些困难.

由于大部分内容都是由Leaflet直接管理的,我不知道将Leaflet地图实例添加为React Component中的状态是否合理.

使用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
        )
    });
})();
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

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

Ros*_*len 41

  • 您不需要自己管理唯一性,即"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>
        );
    }

}
Run Code Online (Sandbox Code Playgroud)


eri*_*oco 21

作为一个额外的,不太详细的答案,PaulLeCam的反应传单组件似乎很受欢迎.尚未使用它但看起来很有希望:

https://github.com/PaulLeCam/react-leaflet

更新:它很稳固.尚未使用过许多功能,但代码库编写得很好,易于遵循和扩展,而且我所使用的功能开箱即用.