超级表达式必须为 null 或函数(自定义标记)

Super expression must either be null or a function (Custom Marker)

我正在创建一个应用程序,用户只需单击地图本身即可将标记添加到地图上的特定位置。为此,我正在使用 react-leaflet 生成地图及其功能。这非常有效,但我希望与标记关联的弹出窗口在创建时打开,但我似乎无法实现。

我尝试按照 获得此功能,并将扩展标记导入我的地图。但是,唉,出现了如下错误:

Super expression must either be null or a function
at _inherits (Marker.js:21)
at eval (Marker.js:30)
at eval (Marker.js?6e37:11)
at Module../src/utils/components/Marker.js (main.js:11547)

这让我很困扰,主要是因为在扩展标记 class 时我似乎找不到关于这个错误的具体答案。这是我的扩展标记实现(再简单不过了):

import { Marker } from 'react-leaflet';

class ExtendedMarker extends Marker {

  componentDidMount() {
    // Call the Marker class componentDidMount (to make sure everything behaves as normal)
    super.componentDidMount();

    // Access the marker element and open the popup.
    this.leafletElement.openPopup();
  }

}

export default ExtendedMarker;  

这是我导入它的地方:

import ExtendedMarker from '../../../utils/components/Marker';

...

createMarker = (key, lat, lng) => {
  const _lat = round(lat, this.DECIMAL_PLACES);
  const _lng = round(lng, this.DECIMAL_PLACES);
  return (
    <ExtendedMarker key={key} id={key} position={[_lat, _lng]}>
      <Popup className={`${styles.popup}`}>
        <Form>
          ...
        </Form>
      </Popup>
    </ExtendedMarker>
  )
}

以下是我使用的版本:

"react-leaflet": "^2.1.2",
"react": "^16.6.1"

有什么建议吗?

谢谢, 吉尔

因为 React official documentation 建议更喜欢组合而不是继承:

At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies.

Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

我建议使用以下标记组件,它演示了如何在创建标记时打开弹出窗口

const ExtendedMarker = props => {

  const openPopup = marker => {
    if (marker) marker.leafletElement.openPopup();
  };

  return (
    <Marker ref={el => openPopup(el)} {...props}/>
  );
};

A callback function 用于通过 marker.leafletElement

访问 Leaflet Marker

Here is a demo供大家参考