我正在做一个将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: '© <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 ) }); })();
所以我的问题是:
getDOMNode
map
state
除了这两点,请正常使用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: '© <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> ); } }