封装组件对外通过 ref 暴露的信息。
常用场景是子组件不希望父组件直接 *** 作 dom,而是通过暴露固定方法
下面方法中,父组件通过 inputRef 只能获取到 value 属性,而没有其他的DOM信息
import React, { useRef, useImperativeHandle, useEffect } from 'react';const Parent = () => { const inputRef = useRef(null); useEffect(() => { setTimeout(() => { if (inputRef.current) { console.log(inputRef.current); inputRef.current.value; } }, 3000); }, []); return <Child ref={inputRef} />}const ChildComponent = ({ propsRef }) => { useImperativeHandle(propsRef, () => ({ value: propsRef.current.value }), [propsRef]); // 这里使用了 uncontrolled component return <input ref={propsRef} defaultValue='xxx' />}const Child = React.forwardRef((props, ref) => { return <ChildComponent {...props} propsRef={ref} />});export default Parent;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)