javascript 结合 React 和 Leaflet 的好方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26755251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:27:04  来源:igfitidea点击:

Good way to combine React and Leaflet

javascriptleafletreactjs

提问by soueuls

I am working on a project to combine React and Leaflet, but I must say I am having some hard time with the semantics.

我正在做一个结合 React 和 Leaflet 的项目,但我必须说我在语义方面遇到了一些困难。

As most of the stuff is managed by Leaflet directly, I don't know if it would make sense to add the Leaflet map instance as state in the React Component or not.

由于大多数东西都是由 Leaflet 直接管理的,我不知道将 Leaflet 地图实例添加为 React 组件中的状态是否有意义。

Same problem when it comes to creating markers with Leaflet, as it does not return anything, I don't have anything to render really. The logic itself seems blurry to me.

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

Here is what I started to make. It's working but I feel like I'm writing bad code and missing the concept.

这是我开始制作的。它正在工作,但我觉得我正在编写糟糕的代码并且缺少概念。

/** @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
        )
    });
})();

So my questions are:

所以我的问题是:

  • Does this sample seem legit?
  • How would you approach the logic of adding markers and managing their events?
  • 这个样本看起来合法吗?
  • 您将如何处理添加标记和管理其事件的逻辑?

回答by Ross Allen

  • You don't need to manage uniqueness, i.e. "UID", yourself. Instead, you can use getDOMNodeto access the component's real node. Leaflet's API supports either a string selector or an HTMLElement instance.
  • Leaflet is managing rendering, so the mapshould not live on state. Only store data in statethat affects React's rendering of the DOM element.
  • 您不需要自己管理唯一性,即“UID”。相反,您可以使用getDOMNode访问组件的真实节点。Leaflet 的 API 支持字符串选择器或 HTMLElement 实例。
  • Leaflet 正在管理渲染,所以不map应该在state. 只存储state影响 React 渲染 DOM 元素的数据。

Beyond those two points, use the Leaflet API normally and tie callbacks from your React component to the Leaflet map as you like. React is simply a wrapper at this point.

除了这两点之外,正常使用 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>
        );
    }

}

回答by ericsoco

As an additional, less-detailed answer, PaulLeCam's react-leaflet component seems popular. Haven't used it yet but it looks promising:

作为额外的、不太详细的答案,PaulLeCam 的 react-leaflet 组件似乎很受欢迎。还没有使用它,但它看起来很有希望:

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

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

UPDATE:It's solid. Haven't used many of the features yet but the codebase is well-written and easy to follow and extend, and what I've used works great out of the box.

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