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

时间:2019-09-18 19:29:12

标签: javascript reactjs

我正在将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 个答案:

答案 0 :(得分:0)

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

useRefcreateRef之间有细微的区别:请参阅这篇文章。
What's the difference between `useRef` and `createRef`?

确保除去功能组件中的this.

function Map() {
  const mapRef = useRef();

  const MyGoogleMap = withScriptjs(
    withGoogleMap(props => <GoogleMap ref={mapRef} />)
  );

  return <MyGoogleMap />;
}