什么是 useImperativeHandle?
本質(zhì)上其實是子組件將自己內(nèi)部的函數(shù)(方法)通過useImperativeHandle添加到父組件中useRef定義的對象中。
useImperativeHandle 允許你自定義通過 ref 暴露給父組件的實例值。通常,我們使用 ref 來訪問組件的 DOM 元素或類組件的實例。但有時,我們可能希望向父組件暴露子組件的某些特定方法,而不是整個實例或 DOM 元素。這時,useImperativeHandle 就派上了用場。
基本用法1
當(dāng)你想從子組件向父組件暴露某些特定的方法時,可以使用 useImperativeHandle。
子組件:

image.png
父組件:
<View id='carView'>
<UserCar
car={car}
combinedSpecification={combinedSpecification}
onClickTyre={() => { ...do something }}
/>
</View>
基本用法2
import React, { useRef, useImperativeHandle, forwardRef } from "react";
// Child
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
sayHello() {
console.log("Hello from Child!");
},
}));
return <div>Child Component</div>;
});
// Parent
function Parent() {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.sayHello();
};
return (
<><Child ref={childRef} /><button onClick={handleClick}>Call Child Method</button></>
);
}
與其他 Hooks 結(jié)合使用
useImperativeHandle 可以與其他 Hooks 如 useState 和 useEffect 結(jié)合使用。
// Child
const Child = forwardRef((props, ref) => {
const [count, setCount] = useState(0);
useImperativeHandle(ref, () => ({
increment() {
setCount((prevCount) => prevCount + 1);
},
decrement() {
setCount((prevCount) => prevCount - 1);
},
}));
useEffect(() => {
console.log(`Count changed to ${count}`);
}, [count]);
return <div>Count: {count}</div>;
});
依賴數(shù)組
useImperativeHandle 的第三個參數(shù)是一個依賴數(shù)組,與 useEffect 和 useMemo 中的依賴數(shù)組類似。這個依賴數(shù)組決定了何時重新創(chuàng)建暴露給父組件的實例方法。當(dāng)依賴數(shù)組中的值發(fā)生變化時,useImperativeHandle 會重新執(zhí)行。
const Child = forwardRef((props, ref) => {
const [count, setCount] = useState(0);
useImperativeHandle(
ref,
() => ({
getCurrentCount() {
return count;
},
}),[count]);
return <div>Count: {count}</div>;
});