React之useImperativeHandle子組件自定義函數(shù)(方法)暴漏給父組件

什么是 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>;
});

結(jié)合useRef、React.forwardRef一起使用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容