react 【ref转发forwardRef】【useImperativeHandle】
前言
ref转发的使用场景比较少见,但是我们在编写组件库的时候,可能会需要使用到他
举个列子
定义了一个FancyButton组件
const FancyBotton = (props: any) => { return (;); };
你需要在使用时暴露button的ref
const App = () => { const ref = useRef(null); return (); };button //这样只能获取FancyButton的ref,而不能转发button的ref
那么我们需要如何在
//使用forwardRef //使用forwardRef之后,它使用时button ,将ref作为组件函数的第二个参数 const FancyButton = react.forwardRef((props: any, ref: any) => { return (;); });
hook
useRef:Reatc.crateRef
useImperativeHandle:自定义转发给父组件的ref的值
useImperativeHanle必须要与ofrwardRef一起使用
const FancyButton = react.forwardRef((props: any, ref: any) => { useImperativeHandle(
//ref ref,
//第二个参数函数返回的值,会作为ref }>button上ref的值,此时为{click:fn} () => { return { click() { console.log("click run"); }, }; }, [deps] ); return (;); });