React Hooks之UseRef ForwardRef useImperativeHandle父子组件通信

宇文曦
2023-12-01

使用场景:需要重复触发子组件弹窗或者需要在子组件数据有变化时可以采用调用子组件身上特定方法执行操作。

需要用到的Api: useRef   useImperativeHandle   forwardRef


简单说明:
1.useRef: 用于获取元素的原生DOM或者获取自定义组件所暴露出来的ref方法(父组件可以通过ref获取子组件,并调用相对应子组件中的方法)

useRef可以用来做数据持久化,也可以用来获取到元素实例

ref.current的变化并不会导致函数组件的重新加载不像useState

可以用一个假的useState,结合useEffect的依赖让useRef的值改变后重新加载函数

import React, { useState, useContext, useRef, useEffect } from "react";
const App = () => {
  const [num, setNum] = useState(0);
  const myRef = useRef(0);
  const btnRef = useRef();
    
  useEffect(() => {
    myRef.current += 1;
  }, [num]);

  return (
    <div>
      <h1>我是Ref:{myRef.current}</h1>
      <button
        ref={btnRef}
        onClick={() => {
          setNum((prev) => prev + 1);
          console.log("button的文字: ", btnRef.current.innerText);//改变ref
        }}
      >
        改变ref
      </button>
    </div>
  );
};

export default App;

2.useImperativeHandle: 在函数式组件中,用于定义暴露给父组件的ref方法。

向父组件暴露子组件的实例(类似于子传父), 需要和forwardRef配合使用

// 子组件
import { myContext } from "./store";
import React, { useState, useContext, useEffect, forwardRef, useImperativeHandle } from "react";
import GrandSon from "./grandSon";

const Child = forwardRef((props, ref) => {
  const { setNum, num } = useContext(myContext);
  const [name, setName] = useState("zs");
  useImperativeHandle(ref, () => {
    return { fn };
  });

  const fn = () => {
    console.log("hahahha");
  };

  return (
    <div ref={ref}>
      <h1>我是子组件</h1>
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum((prev) => prev + 1);
          setName("ls");
        }}
      >
        子组件添加
      </button>
      <GrandSon num={num} name={name} />
    </div>
  );
});

export default Child;

父组件就能获取到暴露的值 

//父组件
import React, { useState, useContext, useRef, useEffect } from "react";
import Child from "./child";

const App = () => {
  const [num, setNum] = useState(0);
  const myRef = useRef(0);
  const btnRef = useRef();
  const childRef= useRef(null);  
  useEffect(() => {
    myRef.current += 1;
    childRef.current?.fn?.();
  }, [num]);

  return (
    <div>
      <h1>我是Ref:{myRef.current}</h1>
      <button
        ref={btnRef}
        onClick={() => {
          setNum((prev) => prev + 1);
          console.log("button的文字: ", btnRef.current.innerText);//改变ref
        }}
      >
        改变ref
      </button>
      <Child ref={childRef}></Child>
    </div>
  );
};

export default App;

3.forwardRef: 将父类的ref作为参数传入函数式组件中,本身props只带有children这个参数,这样可以让子类转发父类的ref,当父类把ref挂在到子组件上时,子组件外部通过forwrardRef包裹,可以直接将父组件创建的ref挂在到子组件的某个dom元素上

子组件使用不能直接 <Child ref={childRef}><Child/>

这样子组件获取不到ref,要用forwordRef把子组件包裹起来传入两个参数(props,ref)

//父组件
import React, { useState, useContext, useRef, useEffect } from "react";
import Child from "./child";

const App = () => {
  const [num, setNum] = useState(0);
  const myRef = useRef(0);
  const btnRef = useRef(null);
  const childRef= useRef(null); 
  useEffect(() => {
    myRef.current += 1;
  }, [num]);

  return (
    <div>
      <h1>我是Ref:{myRef.current}</h1>
      <button
        ref={btnRef}
        onClick={() => {
          setNum((prev) => prev + 1);
          console.log("button的文字: ", btnRef.current.innerText);//改变ref
        }}
      >
        改变ref
      </button>
      <Child ref={childRef}>这是子组件...</Child>
    </div>
  );
};

export default App;

//子组件
import React, {useEffect, forwardRef } from "react";
const Child = forwardRef((props, ref) => {
  console.log("props: ", props, ref);
  const [num, setNum] = useState(0);

  return (
    <div ref={ref}>
      <h1>我是子组件</h1>
      <h1>{num}</h1>
    </div>
    // <div>props.children</div>
  );
});

export default Child;

————————————————

参考: react-hooks之useRef,useImperativeHandle的使用_Shimmer-612的博客-CSDN博客

 

 类似资料: