我遵循了React Locate on map的回答在 Gatsby 开发模式下,一切都运行良好。但是如果我构建我的 gatsby 项目,它会抛出 webpack 错误
"WebpackError: TypeError: Object(...) is not a function".
如果我更改代码
导出默认 withLeaflet(LocateControl);
到
导出默认 withLeaflet(LocateControl);
构建有效,但我在浏览器中收到错误
"TypeError: this.props.leaflet is undefined"
import React, { Component } from "react";
import { withLeaflet } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
class LocateControl extends Component {
componentDidMount() {
const { options, startDirectly } = this.props;
const { map } = this.props.leaflet;
const lc = new Locate(options);
lc.addTo(map);
if (startDirectly) {
// request location update and set location
lc.start();
}
}
render() {
return null;
}
}
export default withLeaflet(LocateControl);
locate-plugin 应该可以工作,但现在构建无法工作。
最佳答案
我遇到了同样的问题,几个小时后这个解决方案对我有用:
locatecontrol.js
import { useEffect } from "react";
import { useLeaflet } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
export default function LocateControl() {
const { map } = useLeaflet();
useEffect(() => {
// geo locate props
const locateOptions = {
position: 'topright',
maxZoom: 19,
strings: {
title: 'Show me where I am, yo!'
},
onActivate: () => {} // callback before engine starts retrieving locations
}
const lc = new Locate(locateOptions);
// console.log(lc);
lc.addTo(map);
}, [map]);
return null;
}
导入到leaflet-map.js
import LocateControl from "./locatecontrol"
并在 map 中使用LocateControl
<Map>
<LocateControl startDirectly/>
</Map>
我是 React 新手,我不确定解决方案是否完全正确 - 但我还没有遇到错误(我们会看到:))并且 gatsby 构建顺利。
也许有人会想出更好的解决方案。
关于gatsby - React-Leaflet 与 leaflet.locatecontrol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57517001/