【问题标题】:Extending a react Symbol(react.forward_ref) from leaflet-react从传单反应扩展反应符号(react.forward_ref)
【发布时间】:2019-03-22 13:46:57
【问题描述】:

我正在从 react-leaflet 导入 Popup

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

并试图扩展它

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()
        }
    }
}

这编译得很好,但是当我在浏览器中运行它时,我收到错误“超级表达式必须为空或函数,而不是对象”

当我控制台记录 Popup 对象时,它看起来像这样

{$$typeof: Symbol(react.forward_ref), render: ƒ, apply: ƒ, bind: ƒ, call: ƒ, …}

而不是 React 组件。我需要以不同的方式导入它吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    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

    【讨论】:

    • 我从这一行 const { map } = this.props.leaflet; 收到“未捕获的类型错误:无法读取未定义的属性 'map'”
    • @psykx,确实,我忘了提到 MyPopup 需要包裹在 withLeaflet HOC 中才能传递 Leaflet 上下文。答案已更新
    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2011-02-10
    • 2011-08-27
    相关资源
    最近更新 更多