从传单反应扩展反应符号(react.forward_ref)

时间:2019-03-22 13:46:58

标签: javascript reactjs

我正在从react-leaflet导入Popup

Property does not override any property from its superclass.

并尝试扩展它

import  { Marker, Map, Popup, TileLayer, ZoomControl, GeoJSON, ScaleControl} from 'react-leaflet'

这可以正常编译,但是当我在浏览器中运行它时,出现错误“超级表达式必须为null或函数,而不是对象”

当我console.log Popup对象时,它看起来像这样

class NewPopup extends Popup  {

    onPopupOpen = ({ popup }: { popup: LeafletElement }) => {
        if (popup === this.leafletElement) {
            console.log("Here open");
            this.onOpen()
        }
    }

    onPopupClose = ({ popup }: { popup: LeafletElement }) => {
        if (popup === this.leafletElement) {
            console.log("Here close");
            this.onClose()
        }
    }
}

而不是React组件。我需要以其他方式导入吗?

1 个答案:

答案 0 :(得分:0)

This thread讨论了为什么发生以下错误:

  

超级表达式必须为null或函数,而不是对象

简短的答案是:Popup库中不支持通过继承扩展react-leaflet组件。实际上,甚至React official documentation都鼓励使用组合而不是继承:

  

在Facebook,我们在成千上万的组件中使用React,但我们尚未   发现了建议使用组件的任何用例   继承层次结构。

     

道具和构图为您提供了所需的所有灵活性   以明确且安全的方式自定义组件的外观和行为。   请记住,组件可以接受任意道具,包括   基本值,React元素或函数。

话虽如此,下面的示例演示了如何自定义Popup组件: (一旦关闭或打开弹出窗口,它将在控制台中显示一条消息)

class MyPopup extends Component {
  componentDidMount() {
    const { map } = this.props.leaflet; //get map instance
    map.on("popupopen", e => {
      console.log(e.popup);
      console.log("Popup opened")
    });
    map.on("popupclose", e => {
      console.log(e.popup);
      console.log("Popup closed")
    });
  }

  render() {
    return <Popup {...this.props} />;
  }
} 

MyPopup组件需要用withLeaflet HOC包装,以便传递Leaflet上下文

Demo