跳到主要内容

认识

2023年02月22日
柏拉文
越努力,越幸运

一、认识


useImperativeHandleReact 中的一个 Hook,它能让你自定义由 ref 暴露出来的句柄。

二、语法


import React,{ useRef } from "react";

const Child = forwardRef((prop,ref)=>{

const childRef: RefObject<{ say: () => void }> = useRef(null);

const fun = ()=>{
childRef.current?.say();
}

return <div>
<h3>子组件</h3>
<Child ref={childRef} />
</div>
});

三、用法


3.1 向父组件暴露元素

import React,{ useRef } from "react";

const Child = forwardRef((prop,ref)=>{

const childRef: RefObject<{ say: () => void }> = useRef(null);

console.log(childRef.current)

return <div>
<h3>子组件</h3>
<Child ref={childRef} />
</div>
});

3.2 向父组件暴露方法

import React,{ useRef } from "react";

const Child = forwardRef((prop,ref)=>{

const childRef: RefObject<{ say: () => void }> = useRef(null);

const fun = ()=>{
childRef.current?.say();
}

return <div>
<h3>子组件</h3>
<Child ref={childRef} />
</div>
});