error
[react] Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
question
如果父组件包含子组件,useRef不能直接用在子组件上,控制台会报错
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

solution
如果希望修改子组件html元素,则使用将函数组件通过用forwradRef包装。父组件中创建的ref转发进子组件
如果希望调用子组件方法,则使用useImperativeHandle,只暴露出父组件需要的方法

在React开发中,遇到警告:Function components cannot be given refs. Attempt to access this ref will fail. 解决方法是使用React.forwardRef()将函数组件包裹,以便在父组件中传递并访问子组件的ref。若需调用子组件方法,可以结合useImperativeHandle使用,暴露必要的方法给父组件。
3010

被折叠的 条评论
为什么被折叠?



