当前位置: 代码迷 >> 综合 >> [react] Warning: Function components cannot be given refs. Attempts to access this ref will fail. Di
  详细解决方案

[react] Warning: Function components cannot be given refs. Attempts to access this ref will fail. Di

热度:76   发布时间:2023-12-12 01:15:54.0

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,只暴露出父组件需要的方法

  相关解决方案