useMapContext在父组件中解构出来的map无法控制地图实例,hooks用法下useMapContext的用法能否烦请详细说明?
despire1119 opened this issue · 1 comments
despire1119 commented
useMapContext在父组件中解构出来的map无法控制地图实例,hooks用法下useMapContext的用法能否烦请详细说明?感谢!
jaywcjlove commented
@despire1119 这里有个示例
react-baidu-map/packages/map/README.md
Lines 99 to 167 in 0e2615b
### useMapContext & Provider | |
通过 React 的 Context 提供了一个`无需`为每层组件手动注入 ~~`map`~~,~~`container`~~ 和 ~~`BMap`~~ 三个属性 `props`,就能在组件树间进行传递。 | |
> 🚧 在 `v2.3.0+` 版本支持 | |
<!--rehype:style=border-left: 8px solid #ffe564;background-color: #ffe56440;padding: 12px 10px;--> | |
```jsx mdx:preview | |
import React from 'react'; | |
import { useState, useRef, useEffect } from 'react'; | |
import { Map, APILoader, useMap, Provider, useMapContext } from '@uiw/react-baidu-map'; | |
const Marker = () => { | |
const { map } = useMapContext(); | |
const container = useRef(null); | |
const { setContainer } = useMap({ | |
zoom: 3, | |
widget: ['GeolocationControl', 'NavigationControl'] | |
}); | |
useEffect(() => { | |
if (container.current) { | |
setContainer(container.current); | |
} | |
}, [container.current]); | |
useEffect(() => { | |
if (map) { | |
// 创建点标记 | |
const marker1 = new BMap.Marker(new BMap.Point(116.404, 39.925)); | |
const marker2 = new BMap.Marker(new BMap.Point(116.404, 39.915)); | |
const marker3 = new BMap.Marker(new BMap.Point(116.395, 39.935)); | |
const marker4 = new BMap.Marker(new BMap.Point(116.415, 39.931)); | |
// 在地图上添加点标记 | |
map.addOverlay(marker1); | |
map.addOverlay(marker2); | |
map.addOverlay(marker3); | |
map.addOverlay(marker4); | |
} | |
}, [map]); | |
return ( | |
<div ref={container} style={{ height: 300 }} /> | |
); | |
} | |
const Demo = () => { | |
return ( | |
<div style={{ width: '100%', height: '300px', overflow: 'auto' }}> | |
<APILoader akay="eYpCTECSntZmw0WyoQ7zFpCRR9cpgHFG"> | |
<Provider> | |
<div> | |
<Marker /> | |
</div> | |
</Provider> | |
</APILoader> | |
</div> | |
); | |
} | |
export default Demo; | |
``` | |
```js | |
import { useMapContext, Provider } from '@uiw/react-baidu-map'; | |
const { BMap, map, container, state, dispatch } = useMapContext(); | |
// => state.BMap | |
// => state.map | |
// => state.container | |
``` |