React hooks子组件暴露方法示例

说明

通常情况下,React 子组件使用父组件的方法或值通过props传递,反过来,父组件如果需要子组件的方法就需要子组件将自己的方法暴露出去。以下是一个实例:

User.tsx

import React, { FC, useEffect, useState, useRef } from 'react';
import { Button, Table } from 'antd';
import UserEdit, { UserEditRef } from './UserEdit';
import { EditFilled } from '@ant-design/icons';

interface User {
  desc?: string;
  name?: string;
}
const User: FC = () => {
  const userEditRef = useRef<UserEditRef>(null);
  const columns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '操作',
      render: (_: string, record: User) => {
        return (
          <EditFilled
            onClick={(e) => {
              userEditRef.current?.open(record);
            }}
          />
        );
      },
    },
  ];
  const [datasource, setDatasource] = useState<User[]>([
    {
      desc: 'I am Tom',
      name: 'Tom',
    },
    {
      desc: 'I am Marry',
      name: 'Marry',
    },
  ]);

  const updateData = (data?: User) => {
    const datas = [data, ...datasource];
    setDatasource(datas);
  };

  return (
    <div>
      <Button
        onClick={() => {
          userEditRef.current.open();
        }}
      >
        新建
      </Button>
      <Table columns={columns} dataSource={datasource} />
      <UserEdit ref={userEditRef} onSave={updateData} />
    </div>
  );
};

export default User;

UserEdit.tsx

import { useState, useImperativeHandle, forwardRef } from 'react';
import { Form, Input, Drawer, Button } from 'antd';

interface User {
  userId?: number;
  desc?: string;
  name?: string;
}

interface PropType {
  onSave: Function;
}

export interface UserEditRef {
  open: (currentUser?: User) => void;
}

const UserEdit = forwardRef<UserEditRef, PropType>((props, ref) => {
  //props
  const { onSave } = props;
  // state
  const [userEditOpen, setUserEditOpen] = useState(false);
  const [currentFormData, setCurrentFormData] = useState<User>();

  // 暴露给父组件的属性,open是打开抽屉的方法
  useImperativeHandle(ref, () => ({
    open: (currentUser?: User) => {
      setUserEditOpen(true);
      setCurrentFormData(currentUser);
    },
  }));

  const onCancel = () => {
    setUserEditOpen(false);
  };

  const onFinish = (values: any) => {
    onSave(values);
    setUserEditOpen(false);
  };

  return (
    <Drawer
      title={
        currentFormData ? '用户 | ' + currentFormData?.name : '用户 | 新建'
      }
      width="auto"
      open={userEditOpen}
      footer={null}
      onClose={onCancel}
      destroyOnClose
    >
      <Form initialValues={currentFormData} onFinish={onFinish}>
        <Form.Item
          label="组名"
          name="name"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="描述" name="desc">
          <Input.TextArea />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button
            htmlType="button"
            onClick={onCancel}
            style={{ marginLeft: 8 }}
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
});

export default UserEdit;

效果预览

1、stackblitz预览
2、InsCode预览

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Vue3中,组件暴露方法有两种常用的方式。一种是通过使用`defineExpose`手动暴露属性和方法,另一种是使用`ref`来绑定组件,并通过访问`变量名.value`来获取组件内的属性和方法。 首先,通过使用`defineExpose`手动暴露属性和方法。在组件中,你可以将需要暴露的属性和方法定义在`defineExpose`内。例如,在组件中定义一个属性`name`和一个方法`sayHello`,然后在`defineExpose`中将它们暴露出来,像这样: ``` // 组件 defineExpose({ name: '组件名称', sayHello() { console.log('Hello from 组件'); } }); ``` 然后,在父组件中,你可以通过`ref`来引用组件,并通过访问`变量名.value`来获取组件暴露出来的属性和方法。像这样: ``` // 父组件模板 <template> <组件 ref="变量名"></组件> </template> // 父组件逻辑 <script> import { ref } from 'vue'; export default { setup() { const 组件引用 = ref(null); // 访问组件暴露的属性和方法 const 组件名称 = 组件引用.value.name; 组件引用.value.sayHello(); return { 组件引用 }; } }; </script> ``` 另外一种方式是通过将组件的实例赋值给一个变量,然后通过`变量名.组件内属性`来获取组件内的属性和方法。例如: <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Vue3/ 父组件 ref 获取组件内属性或方法 组件 defineExpose 暴露方法 或 属性 总结、](https://blog.csdn.net/m0_64494670/article/details/128667877)[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^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Vue 组件三种export暴露方式和import引入方式](https://blog.csdn.net/weixin_41987908/article/details/127490370)[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^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

likepoems

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值