Function components cannot be given refs.Did you mean to use React.forwardRef()?

自己定义的React组件Label

Label.tsx

interface IProps{
  ref:any;
}
const Label = ({ref}:IProps) => {
  return <div ref={ref}>标签</div>
}

希望拿到Label组件的实例.

然而报错:Function components cannot be given refs.Did you mean to use React.forwardRef()?

解决方案:

将ref改成forwardRef
(class组件用ref,函数组件用forwardRef)

Label.tsx

interface IProps{
  forwardRef:any;
}
const Label = ({forwardRef}:IProps) => {
  return <div ref={forwardRef}>标签</div>
}
posted @ 2022-04-24 17:11  胡姐姐  阅读(437)  评论(0编辑  收藏  举报