gatsby - React-Leaflet 与 leaflet.locatecontrol

标签 gatsby react-leaflet

我遵循了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/

相关文章:

javascript - 我正在做一个切换,我想在触发切换功能时更改 div 的背景颜色变化

javascript - 如何在传单ReactJS中的Marker PopUP上显示更多数据

javascript - 使用 react-leaflet 在标记中实现动态 JSX 元素

javascript - React-Leaflet Map 不更新

javascript - Gatsby 控制台警告您的数据中存在冲突的字段类型。在同一个查询中两次使用创建页面时

gatsby - 带有 MarkdownRemark 的多种帖子类型

javascript - Gatsby JS : error TS2451: Cannot redeclare block-scoped variable 'react_1'

jestjs - 修复 react 传单测试错误 : Cannot read property '_layerAdd' of null

javascript - 如何在 react 传单中选择一个区域

gatsby - 修复 Gatsby 中需要 window 的第三方模块