4

有什么办法弹出窗口始终保持打开状态?无需点击即可打开。

预期行为

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

实际行为

http://take.ms/cUej0

4

4 回答 4

19

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

实际上React 官方文档也推荐使用组合而不是继承:

在 Facebook,我们在数以千计的组件中使用 React,我们还没有发现任何建议创建组件继承层次结构的用例。

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

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

const MyMarker = props => {

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

  return <Marker ref={initMarker} {...props}/>
}

解释:

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

这是一个演示

于 2019-02-03T21:51:27.970 回答
13

您可以做的是从 react-leaflet 标记创建自己的 Marker 类,然后在挂载传单对象后在传单对象上调用传单函数 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();
    }
}

一旦组件被安装,这将使弹出窗口打开,并且之后也会像正常的弹出窗口一样,即。关闭/打开。

我将这个小提琴与基本示例一起显示相同的代码。

于 2016-08-16T09:31:40.980 回答
4

你可以使用永久的tooltips,或者 React 为这种类型的东西提供 refs ......你可以这样做:

https://jsfiddle.net/jrcoq72t/121/

const React = window.React
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet

class SimpleExample extends React.Component {
  constructor () {
    super()
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13
    }
  }

  openPopup (marker) {
    if (marker && marker.leafletElement) {
      window.setTimeout(() => {
        marker.leafletElement.openPopup()
      })
    }
  }

  render () {
    const position = [this.state.lat, this.state.lng]
    return (
      <Map center={position} zoom={this.state.zoom}>
        <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
        <Marker position={position} ref={this.openPopup}>
          <Popup>
            <span>
              A pretty CSS3 popup. <br /> Easily customizable.
            </span>
          </Popup>
        </Marker>
      </Map>
    )
  }
}

window.ReactDOM.render(<SimpleExample />, document.getElementById('container'))

参考:

https://reactjs.org/docs/refs-and-the-dom.html

React.js - 访问组件方法

在反应传单地图上自动打开标记弹出

于 2018-12-17T00:53:59.613 回答
4

以上不再适用于 react-leaflet 版本 3。在您的自定义标记组件中,要获取对您现在应该使用的传单元素的引用,然后在安装组件useRef()后打开弹出窗口。useEffect()

const MyMarker = (props) => {
  const leafletRef = useRef();
  useEffect(() => {
    leafletRef.current.openPopup();
  },[])
  return <Marker ref={leafletRef} {...props} />
}
于 2021-03-23T19:27:38.210 回答