猿问

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

我正在将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 }}


噜噜哒
浏览 243回答 1
1回答

慕运维8079593

在Function Component 中,您使用useRef钩子。useRef&之间有细微的区别createRef:请参阅这篇文章。`useRef` 和 `createRef` 有什么区别?确保this.在函数组件中删除。function Map() {&nbsp; const mapRef = useRef();&nbsp; const MyGoogleMap = withScriptjs(&nbsp; &nbsp; withGoogleMap(props => <GoogleMap ref={mapRef} />)&nbsp; );&nbsp; return <MyGoogleMap />;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答