gpt4 book ai didi

reactjs - React 中的 Bing map 组件

转载 作者:行者123 更新时间:2023-12-04 16:42:14 25 4
gpt4 key购买 nike

我想创建组件以使用 TypeScript 在 React.js 中显示 bing map 。
我知道 github 中有很多组件用于此目的。但我想为自己从头开始创建这个组件。
我在 react 中创建了类,并在 componentWillMount 函数中将脚本标记注入(inject)到我的 html 的 head 中:

    componentWillMount() {
const script = document.createElement("script");
var scriptURL = "<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=" + this.props.apiKey + "' ></script>";
const scriptText = document.createTextNode(scriptURL);

script.appendChild(scriptText);
document.head.appendChild(script);
}

当我想创建 map 后跟 this documentcomponentDidMount 函数中是这样的:

componentDidMount() {
var map = new Microsoft.Maps.Map(this.mapElement);
}

我收到此错误:

Cannot find name 'Microsoft'.

我应该如何将“Microsoft”模块导入我的组件?

最佳答案

这是 React BingMaps 组件的极简实现,不依赖于 BingMaps 类型定义。

首先介绍加载BingMaps API和Microsoft类型的服务:

export interface MapWindow extends Window {
Microsoft: any;
}

declare let window: MapWindow;
export let Microsoft: any;


export function loadBingApi(key?: string): Promise<void> {
const callbackName = "bingAPIReady";
let url = `https://www.bing.com/api/maps/mapcontrol?callback=${callbackName}`;
if (key) {
url += `&key=${key}`;
}

return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.defer = true;
script.src = url;
window[callbackName] = () => {
Microsoft = window.Microsoft;
resolve();
};
script.onerror = (error: Event) => {
reject(error);
};
document.body.appendChild(script);
});
}

这是一个接受 mapOptions 作为 props 的 Map 组件:

interface IMapProps {
mapOptions?: any;
}

export default class BingMap extends React.Component<IMapProps, any> {
private mapRef = React.createRef<HTMLDivElement>();

public componentDidMount() {
loadBingApi().then(() => {
this.initMap();
});
}

public render() {
return <div ref={this.mapRef} className="map" />;
}

private initMap() {
const map = new Microsoft.Maps.Map(this.mapRef.current);
if (this.props.mapOptions) {
map.setOptions(this.props.mapOptions);
}
return map;
}
}

用法

<BingMap
mapOptions={{
center: [47.60357, -122.32945],
credentials:
"--BingMaps key goes here--"
}}
/>

Here is a demo

关于reactjs - React 中的 Bing map 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com