Popup始终在标记中打开

Tit*_*txo 2 react-leaflet

有什么方法弹出窗口始终保持开放状态?无需点击它即可打开.

预期的行为

https://monosnap.com/file/mPkuSTmPAfwxTxY99YQVA5m96Zolow.png

实际行为

http://take.ms/cUej0

Vad*_*hev 11

随着引入的引入react-leaflet version 2带来了有关创建自定义组件的重大变化,不再支持通过继承扩展组件(更多信息请参见此线程

实际上,React官方文档还建议使用组合而不是继承:

在Facebook,我们在成千上万的组件中使用React,但还没有找到建议创建组件继承层次结构的用例。

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

以下示例演示了如何扩展标记组件,以便在显示标记后保持弹出窗口的打开状态:

const MyMarker = props => {

  const initMarker = ref => {
    if (ref) {
      ref.leafletElement.openPopup()
    }
  }

  return <Marker ref={initMarker} {...props}/>
}
Run Code Online (Sandbox Code Playgroud)

说明:

获取对本机传单标记对象(leafletElement)的访问权,并通过方法打开弹出窗口Marker.openPopup

这是一个演示


小智 9

你可以做的是从react-leaflet标记创建自己的Marker类,然后在安装后在leaflet对象上调用leaflet函数openPopup().

// Create your own class, extending from the Marker class.
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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将使组件安装后弹出窗口打开,并且之后的行为也会像普通弹出窗口一样,即.关闭/开放.

我把这个小提琴放在一起,显示了与基本示例相同的代码.

  • 嗨,我按照你的建议做了,但我得到了错误:TypeError:Marker不是构造函数.为什么? (2认同)