我正在将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 }}
答案 0 :(得分:0)
在Function Component中,您使用了useRef钩子。
useRef
和createRef
之间有细微的区别:请参阅这篇文章。
What's the difference between `useRef` and `createRef`?
确保除去功能组件中的this.
。
function Map() {
const mapRef = useRef();
const MyGoogleMap = withScriptjs(
withGoogleMap(props => <GoogleMap ref={mapRef} />)
);
return <MyGoogleMap />;
}