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;
相关推荐
FrontAI6 小时前
Next.js从入门到实战保姆级教程:环境配置与项目初始化
react.js·typescript·学习方法
用户3153247795459 小时前
React19项目中 FormEdit / FormEditModal 组件封装设计说明
前端·react.js
Ruihong11 小时前
Vue3 转 React:组件透传 Attributes 与 useAttrs 使用详解|VuReact 实战
vue.js·react.js
橘子编程13 小时前
React 19 全栈开发实战指南
前端·react.js·前端框架
弓.长.14 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-svg(CAPI) — 矢量图形组件
react native·react.js·harmonyos
局i14 小时前
从零搭建 Vite + React 项目:从环境准备到干净项目的完整指南
前端·react.js·前端框架
Lazy_zheng15 小时前
SDD 实战:用 Claude Code + OpenSpec,把 AI 编程变成“流水线”
前端·react.js·ai编程
光影少年15 小时前
如何实现RN应用的离线功能、数据缓存策略?
react native·react.js·掘金·金石计划
弓.长.16 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:rn-placeholder — 骨架屏占位组件
react native·react.js·harmonyos
whuhewei17 小时前
React性能优化
前端·react.js·性能优化