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


    父组件

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

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

    1. import "./App.css";
    2. import React, { useEffect, useRef } from "react";
    3. import RefToGetChild from "./components/RefToGetChild";
    4. import _ from 'lodash';
    5. const App: React.FC = () => {
    6. const childRef = useRef<any>(null);
    7. useEffect(() => {
    8. console.log(_.get(childRef, 'current'));
    9. }, [_.get(childRef, 'current')]);
    10. return (
    11. <div>
    12. <RefToGetChild ref={childRef} message={"子组件: say hello"} />
    13. <button onClick={() => {
    14. const child = _.get(childRef, 'current');
    15. const buttonDom = child.buttonRef.current
    16. buttonDom?.click();
    17. }}>父组件: trigger child button</button>
    18. <button onClick={() => {
    19. const child = _.get(childRef, 'current');
    20. child?.onTest();
    21. }}>父组件: 使用子组件的onTest方法</button>
    22. <div>父组件: 子组件的data {JSON.stringify(_.get(childRef, 'current.data'))}</div>
    23. </div>
    24. );
    25. };
    26. export default App;

    子组件

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

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

    1. import {
    2. forwardRef,
    3. useEffect,
    4. useImperativeHandle,
    5. useRef,
    6. useState,
    7. } from "react";
    8. const RefToGetChild = forwardRef((props:{message:string;}, ref) => {
    9. const [data, setData] = useState({});
    10. const buttonRef = useRef(null);
    11. useEffect(() => {
    12. setTimeout(() => {
    13. const obj = {
    14. a: 1,
    15. b: 2,
    16. c: 3,
    17. d: Array.from({ length: 10 }, (_, i) => ({ id: i })),
    18. };
    19. setData(obj);
    20. }, 1000);
    21. }, []);
    22. const sayHello = () => {
    23. console.log("hello");
    24. };
    25. const onTest = () => {
    26. console.log('test')
    27. }
    28. useImperativeHandle(ref, () => ({
    29. data,
    30. buttonRef,
    31. onTest,
    32. }));
    33. return (
    34. <div>
    35. <button ref={buttonRef} onClick={sayHello}>
    36. {props.message}
    37. </button>
    38. </div>
    39. );
    40. });
    41. export default RefToGetChild

  • 相关阅读:
    rmq nameserver
    日常Git使用自我记录
    Docker 学习笔记一
    如何理解PCBA种三防漆的作用
    Elasticsearch 8.4.1 配置自签名证书和启用Https
    【webrtc】rtp包组帧
    Jenkins汉化设置
    目前世界上有多少种编程语言
    入坑 Hack The Box
    【已解决】VS2008下MFC程序如何设置多语言
  • 原文地址:https://blog.csdn.net/qq_42750608/article/details/133754037