如何将使用compose与withProps的无状态MyMapComponent转为React组件并写入render?
嘿,我来帮你把这个用compose和withProps写的无状态组件转成React类组件,刚好满足你把所有内容放在render的return里的需求~
转换后的React类组件写法
从你提供的props来看,你应该是在用react-google-maps库吧?下面是直接把所有配置放进render返回值里的完整代码:
import React, { Component } from 'react'; // 根据你实际使用的组件导入,比如GoogleMap、Marker这些 import { GoogleMap } from 'react-google-maps'; class MyMapComponent extends Component { render() { return ( <GoogleMap // 把withProps里的配置直接作为组件props传递 googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-lALSE8L0zgfk0vdt73gNTsfalkAggwY&v=3.exp&libraries=geometry,drawing,places" loadingElement={<div style={{ height: "100%" }} />} containerElement={<div style={{ height: "400px" }} />} // 补全了你没写完的容器样式,可按需调整 mapElement={<div style={{ height: "100%" }} />} // 这里可以添加地图的默认配置,比如缩放、中心点 defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }} // 如果原来的组件有接收父组件传的props,直接用this.props获取就行 // 比如 center={this.props.mapCenter} > {/* 要是有子组件比如Marker,直接在这里嵌套即可 */} {/* <Marker position={{ lat: -34.397, lng: 150.644 }} /> */} </GoogleMap> ); } } export default MyMapComponent;
关键转换逻辑说明
- 原来的
compose(withProps(...))本质是给组件注入一组固定的props,在类组件里我们完全可以跳过高阶组件,直接把这些配置作为<GoogleMap>的props传递,这样所有内容都能放在render的return里。 - 如果你原来的
compose里还有其他高阶组件(比如withScriptjs、withGoogleMap,这俩是react-google-maps常用的),也可以选择在导出组件时包裹,不过如果要严格把内容都放在render里,上面的写法就足够了。 - 注意把URL里的
&改成&,JSX里不需要HTML转义字符,直接写&就可以正常解析。
补充场景:如果保留高阶组件
要是你不想完全抛弃compose和withProps,只是想把核心渲染逻辑放进类组件的render里,也可以这么写:
import React, { Component } from 'react'; import { GoogleMap, withScriptjs, withGoogleMap } from 'react-google-maps'; import { compose } from 'redux'; // 或者你用的其他compose工具 class MyMapComponent extends Component { render() { return ( <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }} // 这里处理你的自定义逻辑 /> ); } } export default compose( withProps({ googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyB-lALSE8L0zgfk0vdt73gNTsfalkAggwY&v=3.exp&libraries=geometry,drawing,places", loadingElement: <div style={{ height: "100%" }} />, containerElement: <div style={{ height: "400px" }} />, mapElement: <div style={{ height: "100%" }} />, }), withScriptjs, withGoogleMap )(MyMapComponent);
这种写法把固定props的注入放在导出环节,核心的地图渲染逻辑还是在类组件的render里,也能满足你的需求~
内容的提问来源于stack exchange,提问作者Allu Manikyam
相关产品推荐
相关产品推荐

