首页 > 解决方案 > 将 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; }>'。

有人能帮我吗?

标签: javascriptreactjstypescriptreact-hooks

解决方案


推荐阅读