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>
}