问题
当我使用如下方式调用组件子组件UploadModal并且绑定Ref时React报错“Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?”;
const UploadModalRef = useRef(null);
const openUploadModal = () => {
UploadModalRef.current.open();
}
// ...
<UploadModal ref={UploadModalRef} />
然而当我按照报错提示使用forwardRef包裹子组件UploadModal后依然报错“TypeError: Cannot read properties of null (reading 'open')”无法访问子组件的方法。
解决:
通过useImperativeHandle暴露子组件方法
import { forwardRef, useState, useImperativeHandle } from "react";
export default forwardRef(function UploadModal(props, ref) {
const [Visible, setVisible] = useState(false);
const
open = () => setVisible(true),
;
useImperativeHandle(ref, () => {
return {
open,
}
})
return (
//...
)
})
标签:Function,access,const,useImperativeHandle,open,React,forwardRef,ref From: https://www.cnblogs.com/facingscreen/p/18420288
useImperativeHandle
是 React 中的一个 Hook,它能让你自定义由 ref 暴露出来的句柄。https://zh-hans.react.dev/reference/react/useImperativeHandle