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;

第二步,父组件

这一步跟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;
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中,组件调用组件方法可以通过以下两种方式实现: 1. 使用类组件:在组件中创建一个对组件实例的引用,并将其传递给组件的props。组件在完成挂载时,通过调用组件传递的方法,并将当前组件的实例作为参数传递给该方法。这样,组件就可以通过组件的实例来调用组件方法。 ```jsx // Parent.js class Parent extends Component { // ... handleChildEvent = (ref) => { this.childRef = ref; // 将组件的实例存储到this.childRef中 } handleClick = () => { this.childRef.sendMessage(); // 通过组件的实例调用组件方法 } render () { return ( <> <Child onChildEvent={this.handleChildEvent} /> <button onClick={this.handleClick}>Trigger Child Event</button> </> ); } } ``` ```jsx // Child.js class Child extends Component { componentDidMount () { this.props.onChildEvent(this); // 在组件调用组件传递的方法,并将当前组件的实例作为参数传递给该方法 } sendMessage = () => { console.log('sending message'); } render () { return ( <span>Child</span> ); } } ``` 2. 使用函数组件React Hook:在组件中使用`useImperativeHandle` Hook,将组件方法暴露给组件组件通过创建一个ref,并将其传递给组件的`onRef` prop,从而获取组件的实例,并通过该实例调用组件方法。 ```jsx // Parent.js import { useRef } from 'react'; function Parent() { const childRef = useRef(null); const handleChildEvent = (ref) => { childRef.current = ref; // 将组件的实例存储到childRef中 } const handleClick = () => { childRef.current.sendMessage(); // 通过组件的实例调用组件方法 } return ( <> <Child onRef={handleChildEvent} /> <button onClick={handleClick}>Trigger Child Event</button> </> ); } ``` ```jsx // Child.js import { useImperativeHandle } from 'react'; function Child(props, ref) { const sendMessage = () => { console.log('sending message'); } useImperativeHandle(props.onRef, () => ({ sendMessage })); return <span>Child</span>; } export default React.forwardRef(Child); ``` 以上是两种常用的在React中实现组件调用组件方法的方式。第一种是使用类组件,通过引用传递组件实例的方式进行通信。第二种是使用函数组件React Hook,在函数组件中使用`useImperativeHandle` Hook来暴露组件方法组件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [React 组件调用组件中的方法](https://blog.csdn.net/qq_40738077/article/details/119427313)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值