为了账号安全,请及时绑定邮箱和手机立即绑定

将 React 类组件迁移到函数组件 (React-google-maps)

将 React 类组件迁移到函数组件 (React-google-maps)

噜噜哒 2021-10-21 15:47:54
我正在将react-google-maps库用于一个项目,我找到了一个完美的例子来满足我的需求。它是下面的代码,正如您所看到的,它是一个类组件。class Map extends Component {  constructor(props){    super(props);    this.map = React.createRef();  }  render() {    const MyGoogleMap = withScriptjs(      withGoogleMap(props => (        <GoogleMap          ref={map => {            this.map = map;          }}        />      ))    );    return(      <MyGoogleMap />    );  }}export default Map我想在函数组件中迁移这个类。我不知道如何实现功能组件的行是this.map = React.createRef();和ref={map => { this.map = map }}
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

在Function Component 中,您使用useRef钩子。


useRef&之间有细微的区别createRef:请参阅这篇文章。

`useRef` 和 `createRef` 有什么区别?


确保this.在函数组件中删除。


function Map() {

  const mapRef = useRef();


  const MyGoogleMap = withScriptjs(

    withGoogleMap(props => <GoogleMap ref={mapRef} />)

  );


  return <MyGoogleMap />;

}


查看完整回答
反对 回复 2021-10-21
  • 1 回答
  • 0 关注
  • 242 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信