Flyto error: Hooks can only be called inside of the body of a function component

Flyto error: Hooks can only be called inside of the body of a function component

尝试添加一个按钮,按下该按钮会将地图移动到纽约市。但是每当我尝试使用按钮时,我都会收到错误消息:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

我知道我需要将 flyto 的钩子放入一个函数中,因为它是一个钩子,但是你如何将它与 class 组件结合起来。

代码:

    export default class App extends React.Component {
      constructor() {
        super();
       this.onClickNewYork = this.onClickNewYork.bind(this)
      }
      onClickNewYork() {
        const { map } = useLeaflet();
        map.flyTo([40.730610, -73.935242], 15)
      }
    return (
        <>
        <Button onPress={this.onClickNewYork}>
        <Map center={position} zoom={0}>
         
          <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
         </map>
        </>
  )
}

你不能在 react-leaflet 版本中这样做 2.x。此外,您不能在基于 class 的组件中使用钩子。

通常要获取地图参考,您会使用 withLeaflet HOC 但这仅适用于作为地图子组件放置的组件。

您在这里应该做的是使用 ref 获取地图参考,然后使用它来调用 map.fly()

mapRef = React.createRef();

onClickNewYork() {
    this.mapRef.current.leafletElement.flyTo([40.73061, -73.935242], 15);
}

<Map
   center={position}
   zoom={0}
   style={{ height: "90vh" }}
   ref={this.mapRef}
 >
...

Demo