React通过ref获取子组件的数据和方法

父组件

1) ref必须传值, 否则childRef拿不到子组件的数据和方法

注意: 不一定使用app组件, 其他的任何父组件都可以

import "./App.css";
import React, { useEffect, useRef } from "react";
import RefToGetChild from "./components/RefToGetChild";
import _ from 'lodash';


const App: React.FC = () => {
  const childRef = useRef<any>(null);

  useEffect(() => {
    console.log(_.get(childRef, 'current'));
  }, [_.get(childRef, 'current')]);

  return (
    <div>
      <RefToGetChild ref={childRef} message={"子组件: say hello"} />
      <button onClick={() => {
        const child = _.get(childRef, 'current');
        const buttonDom = child.buttonRef.current
        buttonDom?.click();
      }}>父组件: trigger child button</button>
      <button onClick={() => {
        const child = _.get(childRef, 'current');
        child?.onTest();
      }}>父组件: 使用子组件的onTest方法</button>
      <div>父组件: 子组件的data {JSON.stringify(_.get(childRef, 'current.data'))}</div>
    </div>
  );
};

export default App;

子组件

1) forwardRef作用: 封装组件, 直接将ref参数加在props后面(也可以不使用, 自己props定义一下ref需要传参, 父组件一样传ref就行)

2) useImperativeHandle作用和vue3的defineExpose一样, 存储需要暴露给父组件让其获取的数据和函数

import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";

const RefToGetChild = forwardRef((props:{message:string;}, ref) => {
  const [data, setData] = useState({});
  const buttonRef = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      const obj = {
        a: 1,
        b: 2,
        c: 3,
        d: Array.from({ length: 10 }, (_, i) => ({ id: i })),
      };
      setData(obj);
    }, 1000);
  }, []);

  const sayHello = () => {
    console.log("hello");
  };

  const onTest = () => {
    console.log('test')
  }

  useImperativeHandle(ref, () => ({
    data,
    buttonRef,
    onTest,
  }));

  return (
    <div>
      <button ref={buttonRef} onClick={sayHello}>
        {props.message}
      </button>
    </div>
  );
});

export default RefToGetChild

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值