• react 父组件调用子组件的属性或方法


    前言

    vue3中,

    • 子组件会使用 defineExpose 暴露出父组件需要访问的 变量方法
    • 父组件通过 ref 函数定义子组件的 refName,并通过 refName.value.xxx 继续访问

    react 中呢?

    可使用 useImperativeHandleforwardRefuseRef

    第一步,子组件

    • 使用 useImperativeHandle 定义要暴露出去的内容,第一个参数是 ref
    • forwardRef 包裹 App 组件后,再暴露出去
    import React, { useState, useImperativeHandle, forwardRef } from "react";
    import { Modal, Button } from "antd";
    
    const App = (props, ref) => {
      const [isModalOpen, setIsModalOpen] = useState(false);
      const [data, setData] = useState({});
      
      const showModal = () => {
        setIsModalOpen(true);
      };
      const handleCancel = () => {
        setIsModalOpen(false);
      };
      // 暴露给父组件访问(useImperativeHandle、forwardRef、ref组合使用)
      useImperativeHandle(ref, () => ({
        openModal: (data) => {
          showModal();
          setData(data);
        },
      }));
    
      return (
        <Modal
          title="查看平台详情"
          open={isModalOpen}
          onCancel={handleCancel}
          width={700}
          footer={null}
        >
          <div>
            <Button type="primary" onClick={handleOk}>
              确定
            </Button>
          </div>
        </Modal>
      );
    };
    const Index = forwardRef(App);
    export default Index;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    第二步,父组件

    这一步跟vue3比较接近

    • 父组件通过 useRef 定义子组件的 ref 属性
    • 通过 refName.current.xx 再继续访问子组件暴露出的内容
    import React, { useRef } from "react";
    import { Button } from "antd";
    import Title from "../components/Title";
    import DetailModal from "../components/DetailModal";
    
    // 渲染
    const App = () => {
    
      const detailRef = useRef();
    
      // 查看详情
      function handleDetail(row) {
        detailRef.current.openModal(row);
      }
    
      return (
        <>
          <Title title="境内平台管理">
            <Button type="primary">新建平台</Button>
          </Title>
          <DetailModal ref={detailRef} />
        </>
      );
    };
    export default App;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 相关阅读:
    Java反射详解,还有什么理由学不会
    doT.js模板学习笔记
    11-20==c++知识点
    【锂离子电池常见溶剂】
    面向对象编程之自定义异常处理
    “AI巨浪:ChatGPT等大模型重塑科研与创新的未来!“
    智能井盖是什么?万宾科技智能井盖传感器有什么特点
    VSCode 1.90版本 升级需谨慎~(Python)
    算法通关村第16关【白银】| 滑动窗口经典问题
    uniapp系列
  • 原文地址:https://blog.csdn.net/weixin_42289080/article/details/137964194