父组件调用子组件的函数,获取子组件的变量

关键点:子组件运用了,React.forwardRef,useImperativeHandle
React.memo可要可不要,是我上个分享的代码

import React, { useRef, useState, useImperativeHandle } from 'react';

interface ListProps {
    list: string[];
    id: number;
  }
  

  const List = React.forwardRef(function MyInput(props:ListProps, ref) {
    const {list} = props;

    const count = '这个是子组件变量'
    useImperativeHandle(ref, () => ({
      reload: () => {
        // actionRef?.current?.reload(true)
        console.log('调用了子组件的reload函数')
      },
      getCount:() => count
    }));
    return (
      <div>
          <ul>
            {list.map((it, index) => <li key={index}>{it}</li>)}
          </ul>
      </div>
    );
  });

  // true 不更新 
  // prev props上一个值
  // next props下一个值
  // prev.id === next.id 上一个id和下一个id不相等,子组件才更新
function checkItemEqual(prev, next) {
    return  prev.id === next.id
  }

  export default React.memo(List, checkItemEqual);

父组件调用子组件的函数,获取子组件的变量

import {
  PageContainer,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import React, {  useRef } from 'react';
import List from './components/List';

const TableList: React.FC = () => {
  const ref = useRef(null);


  const handleClick = () => {
    ref.current.reload()
    const parentCount = ref.current.getCount();
    console.log('父组件获取子组件的变量count:', parentCount)

  }
  
  return (
    <PageContainer>
      <Button onClick={handleClick}>调用子组件的方法</Button>
     <List ref={ref} id={5} list={['1','2','3']} />
    </PageContainer>
  );
};

export default TableList;



### Vue3 中父组件调用子组件方法 在 Vue3 中,通过 `ref` 和 `<script setup>` 的组合可以方便地让父组件调用子组件中的方法。具体来说,在子组件内部定义的方法可以通过 `defineExpose` 显式暴露给外部访问。 #### 子组件代码示例如下: ```html <template> <div class="child-component"> <!-- 组件模板 --> </div> </template> <script setup> import { ref } from 'vue' const count = ref(0) // 定义一个可以在父组件中被调用的方法 function incrementCount() { count.value++ } // 使用 defineExpose 将特定属性或函数暴露出去 defineExpose({ incrementCount, }) </script> ``` 当子组件准备好之后,其内声明并暴露出的任何东西都可以通过由父级传递过来的一个带有 `.ref` 属性绑定的对象来获取到[^1]。 #### 父组件代码如下所示: ```html <template> <div class="parent-container"> <button @click="invokeChildMethod">点击增加计数器</button> <!-- 使用 ref 来引用子组件实例 --> <ChildComponent ref="childRef"/> </div> </template> <script setup> import { ref, onMounted } from 'vue' import ChildComponent from './path/to/ChildComponent.vue' // 创建用于存储子组件实例的变量 const childRef = ref(null) // 定义用来触发子组件方法的函数 function invokeChildMethod() { if (childRef.value && typeof childRef.value.incrementCount === 'function') { childRef.value.incrementCount() } } </script> ``` 上述例子展示了如何利用 `ref` 关键字创建对子组件实例的引用,并且通过该引用来直接调用已公开的方法。这使得父子之间能够安全有效地交互操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值