这是我的组件
import React, { PropTypes } from 'react';
import { MapLayer } from 'react-leaflet';
import L from 'leaflet';
import './collision.js';
export default class LayerGroupCollision extends MapLayer {
static childContextTypes = {
layerContainer: PropTypes.shape({
addLayer: PropTypes.func.isRequired,
removeLayer: PropTypes.func.isRequired,
})
}
getChildContext() {
return {
layerContainer: this.leafletElement,
}
}
createLeafletElement() {
var t = L.layerGroup.collision({ margin: 20 }, this.getOptions());
this.layerContainer.addLayer(t);
return t;
}
componentDidMount() {
const {map} = this.context;
map.on("zoomend", this._onZoomEnd);
}
componentWillUnmount() {
const {map} = this.context;
map.off("zoomend", this._onZoomEnd);
}
}
但这不起作用,我只是得到了标记。 在变焦时我得到错误
未捕获的TypeError:无法读取属性' call'未定义的
at NewClass.fire (leaflet-src.js:587) at NewClass._moveEnd (leaflet-src.js:3432) at NewClass.<anonymous> (leaflet-src.js:3869)
有什么建议吗?
答案 0 :(得分:1)
你没有在你的类中定义_onZoomEnd
函数,而你扩展的MapLayer类也没有。
但是在map.on("zoomend", this._onZoomEnd)
和map.off("zoomend", this._onZoomEnd)
中,您将其作为zoomend事件的回调提供。
然后它无法调用_onZoomEnd,因为它未定义
答案 1 :(得分:0)
插件本身负责定义侦听器,因此您可以省略该代码。下面的代码应该足以将Leaflet.LayerGroup.Collision插件包装在React组件中。 Alex的评论是正确的,因为您收到错误消息。
import React from 'react';
import { func, shape } from 'prop-types';
import { MapLayer } from 'react-leaflet';
import 'leaflet.layergroup.collision';
import L from 'leaflet';
export default class LayerGroupCollision extends MapLayer {
static childContextTypes = {
layerContainer: shape({
addLayer: func.isRequired,
removeLayer: func.isRequired,
}),
}
getChildContext() {
return {
layerContainer: this.leafletElement,
};
}
createLeafletElement() {
const layerGroup = L.layerGroup.collision({ margin: 4 });
this.layerContainer.addLayer(layerGroup);
return layerGroup;
}
}