如何使用 React 传单上下文?
How to use react leaflet context?
我正在尝试访问 React 传单上下文,但我不明白它是如何工作的
这是我尝试过的:
import { Map, TileLayer, Marker, Popup, LeafletContext } from 'react-leaflet';
...
render() {
<Map
center={position}
zoom={zoomInit}
onClick={this.handleClick}
ref={this.mapRef}
whenReady={this.mapReady}
>
<TileLayer id='id' accessToken='accessToken' attribution="attribution" url="url"/>
<LeafletContext.LeafletConsumer>
{
map => console.log(map)
}
</LeafletContext.LeafletConsumer>
</Map>
我想知道如何导入 LeafletContext ?
然后我想了解如何获取地图参考?
我想访问它,因为文档说它可以访问地图。我尝试通过 react ref 访问地图,但可用性有点随机。
constructor(props) {
super(props)
setTimeout(this.test, 1000)
}
componentDidMount () {
console.log(this.mapRef.current); // undefined
}
mapReady = () => {
console.log(this.mapRef) // undefined
}
test() {
console.log(this.mapRef.current.leafletElement) // Ok, shows map object
}
中所述
The context provider and consumer are exported as LeafletProvider
and LeafletConsumer
你需要导入LeafletConsumer
(不是LeafletContext)
import { LeafletConsumer } from 'react-leaflet';
此外,上下文对象具有以下形状
type LeafletContext = {
map?: Map,
pane?: ?string,
layerContainer?: ?LayerContainer,
popupContainer?: ?Layer,
}
所以你需要在你的渲染方法中像这样使用它
<LeafletConsumer>
{context => console.log(context.map)}
</LeafletConsumer>
我正在尝试访问 React 传单上下文,但我不明白它是如何工作的
这是我尝试过的:
import { Map, TileLayer, Marker, Popup, LeafletContext } from 'react-leaflet';
...
render() {
<Map
center={position}
zoom={zoomInit}
onClick={this.handleClick}
ref={this.mapRef}
whenReady={this.mapReady}
>
<TileLayer id='id' accessToken='accessToken' attribution="attribution" url="url"/>
<LeafletContext.LeafletConsumer>
{
map => console.log(map)
}
</LeafletContext.LeafletConsumer>
</Map>
我想知道如何导入 LeafletContext ?
然后我想了解如何获取地图参考?
我想访问它,因为文档说它可以访问地图。我尝试通过 react ref 访问地图,但可用性有点随机。
constructor(props) {
super(props)
setTimeout(this.test, 1000)
}
componentDidMount () {
console.log(this.mapRef.current); // undefined
}
mapReady = () => {
console.log(this.mapRef) // undefined
}
test() {
console.log(this.mapRef.current.leafletElement) // Ok, shows map object
}
The context provider and consumer are exported as
LeafletProvider
andLeafletConsumer
你需要导入LeafletConsumer
(不是LeafletContext)
import { LeafletConsumer } from 'react-leaflet';
此外,上下文对象具有以下形状
type LeafletContext = {
map?: Map,
pane?: ?string,
layerContainer?: ?LayerContainer,
popupContainer?: ?Layer,
}
所以你需要在你的渲染方法中像这样使用它
<LeafletConsumer>
{context => console.log(context.map)}
</LeafletConsumer>