React-leaflet 如何获取地图边界并将其居中?

Pat*_*ató 7 react-leaflet

我想这个地图边界和中心,它 映射
我试图用的getBounds()和getCenter(),但它是不确定的。
然后我找到了这个,但它说无法读取未定义的属性“leafletElement”
感谢您的帮助。

class FortMap extends Component {
  state = {
    lat: 51.505,
    lng: -0.09,
    zoom: 18,
  }

  componentDidMount(){
    console.log(this.refs.map.leafletElement.getBounds);
  }

  
  render() {
    const { lat , lng , zoom } = this.state;
    const position = [0, 0];

    return (
        <Map center={position} zoom={zoom}>
          <TileLayer
            url={fortniteMap}
            attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
          />
        </Map>
    )
  }
}

export default FortMap;
Run Code Online (Sandbox Code Playgroud)

Vad*_*hev 5

似乎您忘记refMap组件分配属性:

<Map ref='map' center={position} zoom={zoom}>
  ...
</Map>
Run Code Online (Sandbox Code Playgroud)

获取对传单实例的引用:

componentDidMount(){
    let mapInst =  this.refs.map.leafletElement;
}
Run Code Online (Sandbox Code Playgroud)

演示

  • refs 已弃用 (3认同)