Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useMapContext在父组件中解构出来的map无法控制地图实例,hooks用法下useMapContext的用法能否烦请详细说明? #313

Open
despire1119 opened this issue Sep 8, 2023 · 1 comment

Comments

@despire1119
Copy link

useMapContext在父组件中解构出来的map无法控制地图实例,hooks用法下useMapContext的用法能否烦请详细说明?感谢!

@jaywcjlove
Copy link
Member

@despire1119 这里有个示例

### 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
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants