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;
相关推荐
PineappleCoder2 小时前
React 18 开发完全指南:从环境搭建到调试优化
前端·react.js
GISer_Jing10 天前
React Next快速搭建前后端全栈项目并部署至Vercel
前端·react.js·前端框架
伍哥的传说10 天前
React 轻量级状态管理器Zustand
前端·javascript·react.js·小程序·前端框架·ecmascript
一嘴一个橘子10 天前
react 的过渡动画
react.js
巴巴_羊10 天前
React 新钩子useImperativeHandle
前端·javascript·react.js
訾博ZiBo10 天前
开源分享:我开发了一个智能文本提取浏览器插件,彻底解决复制粘贴的烦恼
前端·react.js·html
萌萌哒草头将军10 天前
什么?React 中可以写 SolidJS 了?SolidJS 官方出手了 🚀🚀🚀
前端·vue.js·react.js
今日亦是美好的一天10 天前
使用Tailwind CSS和i18n的react实践
前端·react.js·前端框架
niusir10 天前
彻底搞懂 useEffect:依赖项、清除函数与常见陷阱
前端·javascript·react.js
niusir10 天前
理解 React 的渲染机制:为什么组件会重新渲染?
前端·javascript·react.js