当前位置: 首页> 财经> 股票 > React@16.x(30)useImperativeHandle

React@16.x(30)useImperativeHandle

时间:2025/7/9 3:37:38来源:https://blog.csdn.net/qq_40147756/article/details/139584708 浏览次数:0次

目录

  • 1,介绍
  • 2,使用

1,介绍

在介绍 ref 时提到,ref 不能作用于函数组件,所以有了 ref 转发。

举例:

function Child(props, ref) {return <h1 ref={ref}>child</h1>;
}const ChildWrap = React.forwardRef(Child);export default function App() {const refChild = useRef();return (<><ChildWrap ref={refChild}></ChildWrap><buttononClick={() => {console.log(refChild.current);}}>获取Child组件</button></>);
}

useImperativeHandle 的作用:在 ref 转发的前提下,为了更方便的在函数组件中使用 ref

2,使用

其他代码不变,只对子组件做如下修改:

function Child(props, ref) {useImperativeHandle(ref,() => {return 123; // 相当于 ref.current = 123},[]);// 此时 h1 上的 ref 失效。return <h1 ref={ref}>child</h1>;
}

同样的,依赖项不变,该HOOK的回调函数不会再次执行。

此时在父组件中获取的 refChild.current 就是 123。
所以如果想通过父组件调用子组件的一些方法,可以将这些方法放到 useImperativeHandle 的第2个参数中即可:

function Child(props, ref) {useImperativeHandle(ref,() => {return {method1() {console.log("method1");},method2() {console.log("method2");},};},[]);return <h1>child</h1>;
}

父组件调用:refChild.current.method1()


以上。

关键字:React@16.x(30)useImperativeHandle

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: