【发布时间】:2020-04-25 17:41:31
【问题描述】:
我正在为 react-leaflet 编写一个自定义组件。这是一个可编辑的弹出窗口,还有一些其他功能。以Here is a codesandbox 为例。该组件的源代码是here。这个例子只是做了一个import EditablePopup from 'my-react-leaflet-popup-plugin',这是我项目中的一个.js文件。效果很好。
我正在尝试使用 webpack 将其打包为节点模块,以便其他人可以使用它。它编译没有问题。你可以看到我的 webpack.config.js here。然后我使用npm link 将此模块链接到我本地机器上的测试项目中。当我这样做时,我收到错误消息:
TypeError: Cannot read property 'leafletElement' of null
460 | value: function value() {
461 | var e = this;
462 | this.props.open && setTimeout(function () {
> 463 | e.thePopup.leafletElement._source.openPopup();
| ^ 464 | }, .001);
465 | }
466 | }, {
即使我去掉那个子句,我也会得到这个:
TypeError: Cannot read property 'openPopup' of undefined
9226 | // @method openOn(map: Map): this
9227 | // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
9228 | openOn: function openOn(map) {
> 9229 | map.openPopup(this);
| ^ 9230 | return this;
9231 | },
9232 | onAdd: function onAdd(map) {
就像弹出窗口试图将自己添加到地图,但没有找到父地图组件的地图实例。我的预感是,由于某种原因,当使用 webpack 构建它并将其作为 npm 模块导入时,react-leaflet 映射的上下文没有正确传递给我的组件。我不太明白,因为我的组件只是 react-leaflet 的 <Popup> 组件的修饰版本。我的<EditablePopup> 使用<Popup> 作为直接子级,它本质上应该接收 LeafletConsumer 上下文消费者包装器。
我不确定为什么这个组件在我的项目中链接时效果很好,但是在通过 webpack 构建并通过 npm 导入时出现此错误。
【问题讨论】:
标签: reactjs webpack custom-component react-leaflet