Hon*_*ota 2 typescript reactjs react-google-maps
我需要在 React
Const mapRef 返回错误中为我的谷歌地图设置新的纬度和经度:对象可能为“空”。TS2531
当我使用 let 而不是 React.useRef 时它可以工作。
我认为应该将类型设置为mapRef,但我不知道是哪一个以及在哪里可以找到它。
但我认为 useRef 是更好的解决方案,不是吗?
谷歌地图库:https://www.npmjs.com/package/@react-google-maps/api
const libraries = ["places"];
const CustomMap = () => {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: "MY_API_KEY",
libraries,
});
const options = {
disableDefaultUI: true,
zoomControl: true,
};
const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);
const panTo = React.useCallback(({ lat, lng }) => {
if (null !== mapRef.current) {
// There is error
// mapRef.current Object is possibly 'null'. TS2531
mapRef.current.panTo({ lat, lng });
mapRef.current.setZoom(18);
}
}, []);
//console.log("maps show coord: ", props.coordinates);
if (loadError) {
return (
<Fragment>
<p>Error</p>
</Fragment>
);
}
if (!isLoaded) {
return (
<Fragment>
<p>loading</p>
</Fragment>
);
}
return (
<div>
<Search panTo={panTo} />
<GoogleMap
id="map"
mapContainerStyle={mapContainerStyle}
zoom={15}
center={center}
//options={options}
onLoad={onMapLoad}
/>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
使用此包查找类型,然后设置类型useRef并使用 初始化它null。
const mapRef: Type = React.useRef(null); // Replace `Type` with the actual type from the package
Run Code Online (Sandbox Code Playgroud)
在你的情况下,类型似乎是google.maps.Map这样
const mapRef: google.maps.Map = React.useRef(null);
Run Code Online (Sandbox Code Playgroud)
应该可以解决问题。
| 归档时间: |
|
| 查看次数: |
6315 次 |
| 最近记录: |