javascript - 将 Hooks 转换为类组件
问题描述
我对 React 有点陌生,我正在开发一个集成 Google Maps 的应用程序。我的代码正在使用 Hooks,但现在我想将其转换为类组件,但我很难做到。我对 useEffect、useRef 和 useState 感到很困惑。这是我的尝试,但我遇到了错误。有人可以帮我正确转换吗?
import React, { useEffect, useRef, useState } from 'react';
import './Map.css';
import { IMapState } from './IMapState';
import { IMapProps } from './IMapProps';
type GoogleLatLng = google.maps.LatLng;
type GoogleMap = google.maps.Map;
export class Map3 extends React.Component<IMapProps, IMapState> {
constructor(props: IMapProps) {
super(props);
this.state = {
mapType: google.maps.MapTypeId,
mapTypeControl: false
};
}
public render(): JSX.Element {
const {
mapType,
mapTypeControl
} = this.state;
const ref = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<GoogleMap>();
const startMap = (): void => {
if (!map) {
defaultMapStart();
}
};
useEffect(startMap, [map]);
const defaultMapStart = (): void => {
const defaultAddress = new google.maps.LatLng(40.166013499, -82.9071); //Ohio LatLong
initMap(5, defaultAddress);
};
const initMap = (zoomLevel: number, address: GoogleLatLng): void => {
if (ref.current) {
setMap(
new google.maps.Map(ref.current, {
zoom: zoomLevel,
center: address,
mapTypeControl: mapTypeControl,
streetViewControl: false,
rotateControl: false,
scaleControl: true,
fullscreenControl: false,
panControl: false,
zoomControl: true,
gestureHandling: 'cooperative',
mapTypeId: mapType,
draggableCursor: 'pointer',
})
);
}
};
return (
<div ref={ref} className="map-container"></div>
);
};
}
当我在另一个 TSX 文件中调用它时,它看起来像这样,但这是错误的:
{scriptLoaded && (
<Map3
mapType={google.maps.MapTypeId.ROADMAP}
mapTypeControl={true}
/>
)}
它说:类型'{ mapType:MapTypeId; mapTypeControl:布尔值;}' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'。属性“mapType”不存在于类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'。
有人能帮我吗?
解决方案
推荐阅读
- spring - 如何使用基本身份验证保护 Spring Cloud Eureka 服务?
- angularjs - 设置选择的某些选项
- c# - Unity 没有找到另一个 DLL 的 DLL 依赖项(都在 Assets 文件夹中)
- javascript - 使用 lodash 将服务响应对象值转换为数组
- javascript - HeadFirst JS:代码示例中的问题
- visual-studio - 在 Visual Studio 发布任务中将字符串数组发送到 Powershell
- jobs - 为有限时间安排每小时 FW 作业 | 奥特系统
- c++ - 安装 Folly (c++ library) 通过 vcpkg 给出错误
- python-3.x - Azure Web 应用程序上 Python Websockets 的主机名和端口
- python - 将 numpy 数组转换为 Shapely Points 的最有效方法是什么?