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;
相关推荐
AAA阿giao9 小时前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
摘星编程1 天前
React Native鸿蒙版:Image图片占位符
react native·react.js·harmonyos
飞羽殇情1 天前
基于React Native鸿蒙跨平台开发构建完整电商预售系统数据模型,完成参与预售、支付尾款、商品信息展示等
react native·react.js·华为·harmonyos
摘星编程1 天前
React Native + OpenHarmony:ImageSVG图片渲染
javascript·react native·react.js
摘星编程1 天前
OpenHarmony + RN:Text文本书写模式
javascript·react native·react.js
xixixin_1 天前
【React】中 Body 类限定法:优雅覆盖挂载到 body 的组件样式
前端·javascript·react.js
摘星编程1 天前
用React Native开发OpenHarmony应用:Image网络图片加载
javascript·react native·react.js
摘星编程1 天前
OpenHarmony环境下React Native:ImageBase64图片显示
javascript·react native·react.js
摘星编程1 天前
React Native鸿蒙:Image本地图片显示
javascript·react native·react.js
2501_921930831 天前
基础入门 React Native 鸿蒙跨平台开发:Video 全屏播放与画中画 鸿蒙实战
react native·react.js·harmonyos