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

前言

在vue3中,

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

react 中呢?

可使用 useImperativeHandleforwardRefuseRef

第一步,子组件

  • 使用 useImperativeHandle 定义要暴露出去的内容,第一个参数是 ref
  • forwardRef 包裹 App 组件后,再暴露出去
js 复制代码
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;

第二步,父组件

这一步跟vue3比较接近

  • 父组件通过 useRef 定义子组件的 ref 属性
  • 通过 refName.current.xx 再继续访问子组件暴露出的内容
js 复制代码
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;
相关推荐
kk不中嘞2 天前
浅谈前端框架
前端·vue.js·react.js·前端框架
小鱼儿亮亮2 天前
二、React基础精讲:编写TodoList、事件绑定、JSX语法、组件之间传值
前端·react.js
小鱼儿亮亮2 天前
五、Redux进阶:UI组件、容器组件、无状态组件、异步请求、Redux中间件:Redux-thunk、redux-saga,React-redux
前端·react.js
wordbaby2 天前
解锁时光机:用 React Hooks 轻松实现 Undo/Redo 功能
前端·react.js
LFly_ice2 天前
学习React-9-useSyncExternalStore
javascript·学习·react.js
醉方休2 天前
React中使用DDD(领域驱动设计)
前端·react.js·前端框架
学习3人组2 天前
React 样式隔离核心方法和最佳实践
前端·react.js·前端框架
乖女子@@@2 天前
React笔记_组件之间进行数据传递
javascript·笔记·react.js
Zacks_xdc2 天前
【前端】使用Vercel部署前端项目,api转发到后端服务器
运维·服务器·前端·安全·react.js
张迅之2 天前
【React】Ant Design 5.x 实现tabs圆角及反圆角效果
前端·react.js·ant-design