React+TypeScript使用react-google-maps的Props类型定义问题
解决react-google-maps与TypeScript的Props类型冲突问题
这个问题确实是react-google-maps的高阶组件组合(compose)和TypeScript类型推断的常见冲突,核心原因是你没有正确给高阶组件传递泛型参数,导致TS无法识别自定义的data属性。下面是两种正确的写法,以及问题的根源解释:
正确写法1:直接给withGoogleMap传递泛型参数
首先定义你的组件Props接口(建议具体化data的类型,不要用any):
// 替换成HeatmapLayer实际需要的data类型,比如google.maps.visualization.WeightedLocation[] interface IGoogleMapComponentProps { data: Array<google.maps.visualization.WeightedLocation>; }
然后修改组件定义,给withGoogleMap传递泛型参数,同时在内部组件里明确Props类型:
const GoogleMapComponent = compose( withProps({ googleMapURL: "url", // 这里替换成你的Google Maps API实际URL loadingElement: <div style={{ height: `100%` }} />, containerElement: <div style={{ height: `400px` }} />, mapElement: <div style={{ height: `100%` }} />, }), withScriptjs, // 告诉withGoogleMap我们的组件接收IGoogleMapComponentProps类型的参数 withGoogleMap<IGoogleMapComponentProps> )((props: IGoogleMapComponentProps) => { console.log(props.data); // 此时TS不会再报错 return ( <GoogleMap defaultZoom={9} defaultCenter={{ lat: -34.397, lng: 150.643 }}> <HeatmapLayer data={props.data} /> </GoogleMap> ); });
正确写法2:拆分内部组件为独立的FC
如果你更喜欢拆分组件结构,可以把地图内容部分定义成独立的函数组件,再传给withGoogleMap:
interface IGoogleMapComponentProps { data: Array<google.maps.visualization.WeightedLocation>; } // 独立定义地图内容组件,明确Props类型 const MapContent: React.FC<IGoogleMapComponentProps> = (props) => { return ( <GoogleMap defaultZoom={9} defaultCenter={{ lat: -34.397, lng: 150.643 }}> <HeatmapLayer data={props.data} /> </GoogleMap> ); }; // compose组合高阶组件,此时TS会自动推导MapContent的Props类型 const GoogleMapComponent = compose( withProps({ googleMapURL: "url", loadingElement: <div style={{ height: `100%` }} />, containerElement: <div style={{ height: `400px` }} />, mapElement: <div style={{ height: `100%` }} />, }), withScriptjs, withGoogleMap )(MapContent);
为什么原来的写法会报错?
- 第一种错误:你直接给
compose的结果指定React.ComponentClass<{}>,但这个类型不包含data属性,所以TS会提示data不存在。 - 第二种错误:当你改成
React.ComponentClass<IProps>时,compose返回的组件类型是由内部高阶组件(withScriptjs、withGoogleMap)共同决定的,手动指定的类型和实际推导的类型不匹配,导致TS认为组件不接收data属性。
通过给withGoogleMap传递泛型参数,或者拆分出明确类型的内部组件,我们让TS正确识别组件的Props结构,解决类型冲突问题。
内容的提问来源于stack exchange,提问作者yerassyl
相关产品推荐
相关产品推荐

