react Hook+antd封装一个优雅的弹窗组件

前言

在之前学vue2的时候封装过一个全局的弹窗组件,可以全局任意地方通过this调用,这次大创项目是用react技术栈,看了一下项目需求,突然发现弹窗还是比较多的,主要分为基础的弹窗以及form表单式的弹窗,如果只是无脑的去写代码,那些项目也没啥必要了。正好react和hook相结合,去实现一个全局的弹窗组件,便于之后的使用。

心血历程

antd组件的弹窗一般是和我们的代码放一起的,这样就导致复用性比较低,而且也显得代码比较乱。由此我就想过自己封装一个,有了之前使用vue封装的经验,我开始着手封装,基本思路就是创建一个新的div放到页面中,手动的渲染与删除,确定和取消按钮正好对应promise的成功与失败。基本思路没有问题,但是再实行的过程中,首先遇到手动渲染挂载到页面的问题,之后又遇到逻辑放到一起,无法手动控制form表单,最后突然想清楚一点就是,逻辑可以分开,把一个功能的相同点与不同点进行分离,逻辑上要单纯,最后再整合到一起。这样的话可以专注于具体的逻辑功能及实现。

代码
modal.tsx

封装的弹窗具体功能,其中根据类型的不同会用到form的高阶组件

import React, { useCallback, useEffect } from "react";
import ReactDOM from "react-dom/client";
import { Button, Modal } from "antd";
import { useState } from "react";
import { useForm } from "./form";
type PromiseType = {
  resolve?: any;
  reject?: any;
};
// modal类型(分为普通或者表单形式)
type modalType = "nomal" | "form";
/* 
成功之后的回调函数
显示标题
提示文字(用于普通类型文本提示)
成功文字
配置对象(字段名,规则,默认值)
*/
type modalPropsType = {
  type?: modalType;
  title?: string;
  infoTxt?: string;
  okTxt?: string;
  successCallback?: (values?: any) => void;
  formOptions?: any;
};

export const useModal = (props: modalPropsType = {}) => {
  const {
    type = "nomal",
    title = "提示",
    infoTxt = "这是一段提示",
    okTxt = "确定",
    successCallback = () => {},
    formOptions = [],
  } = props;
  const [show, setShow] = useState<boolean>(false);
  const [promiseRes, setPromiseRes] = useState<PromiseType>();
  const [containerEle, setContainerEle] = useState<HTMLElement | null>(null);
  // 节点的挂载与卸载
  useEffect(() => {
    if (containerEle) {
      return;
    }
    // 创建挂载节点
    const div = document.createElement("div");
    div.id = "myContainer";
    document.body.append(div);
    setContainerEle(div);
  }, [containerEle]);
  // 卸载节点
  const unMounted = useCallback(() => {
    if (containerEle) {
      document.body.removeChild(containerEle);
      setContainerEle(null);
    }
  }, [containerEle]);

  const success = useCallback(
    (values: any) => {
      successCallback && successCallback();
      promiseRes?.resolve(type === "nomal" ? "确定" : values);
      setShow(false);
      unMounted();
    },
    [promiseRes, unMounted, successCallback, type],
  );
  // 取消
  const cancel = useCallback(() => {
    promiseRes?.reject("取消");
    setShow(false);
    unMounted();
  }, [unMounted, promiseRes]);
  // 获取包装节点
  const { MyForm } = useForm({ cancel, success, okTxt, options: formOptions });
  // 挂载节点
  useEffect(() => {
    if (!show || !containerEle) {
      return;
    }
    const root = ReactDOM.createRoot(containerEle as HTMLElement);
    // 根据类型,去判断是简单的弹窗还是form表单
    root.render(
      <Modal
        onCancel={cancel}
        open={show}
        onOk={success}
        destroyOnClose={true}
        title={title}
        okText={okTxt}
        wrapClassName="modal-wrap"
        cancelButtonProps={{ shape: "round" }}
        okButtonProps={{ shape: "round" }}
        width={600}
        footer={
          type === "form"
          ? null
          : [
            <Button key="success" type="primary" onClick={success}>
              {okTxt}
            </Button>,
            <Button key="cancel" onClick={cancel}>
              取消
            </Button>,
          ]
        }
        getContainer={containerEle as HTMLElement}
        >
        {type === "form" && <MyForm></MyForm>}
        {type === "nomal" && <p>{infoTxt}</p>}
      </Modal>,
    );
  }, [
    show,
    MyForm,
    cancel,
    containerEle,
    title,
    infoTxt,
    okTxt,
    success,
    type,
  ]);
  // 初始化
  const init = () => {
    setShow(true);
    return new Promise((resolve, reject) => {
      setPromiseRes({ resolve, reject });
    });
  };
  return { init };
};
from.tsx

封装的form表单(待完善)

import { Button, Form, FormInstance, Input, Space } from "antd";
import React from "react";
import { useCallback } from "react";

/* 
传递配置对象()
1. 成功回调
2.失败回调
3.配置对象(自动生成form表单)
*/
type formProp = {
  success: (values: any) => void;
  cancel: () => void;
  okTxt: string;
  options?: any;
};

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
export const useForm = (formProp: formProp) => {
  const { success, cancel, okTxt } = formProp;
  const MyForm = () => {
    const formRef = React.useRef<FormInstance>(null);
    const onFinish = useCallback((values: any) => {
      console.log(values);
      success(values);
    }, []);
    const onFinishFailed = useCallback((values: any) => {
      console.log(values);
    }, []);
    const onReset = () => {
      formRef.current?.resetFields();
    };
    return (
      <Form
        ref={formRef}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        autoComplete="off"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        >
        <Form.Item<FieldType>
          label="Username"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
          >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="Password"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
          >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Space wrap>
            <Button type="primary" htmlType="submit">
              {okTxt}
            </Button>
            <Button danger htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button onClick={cancel}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    );
  };

  return {
    MyForm,
  };
};

使用
//可以传递type来指定类型
const nomalMadal=useModal()
//执行该函数开启弹窗
const show=()=>{
  nomalMadal.init()
    .then((res) => {
      console.log("确定", res);
    })
    .catch((err) => {
      console.log("取消", err);
    });
}
总结

在之后的学习过程中,要多换思路,不必拘谨于一个点,要把思维发散,逻辑可以多种方法实现,还有就是源码的能力,之后要多学一下源码,了解源码的思想还有实现方法,这样才能更好的玩转第三方库,如果只是简单的使用,那一个小白,培训个几个月也能达到使用的程度,要有自己的见解和自己的优势。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的可编辑表格的示例代码,使用React HookAntd组件库: ```javascript import React, { useState } from 'react'; import { Table, Input, InputNumber, Popconfirm, Form } from 'antd'; const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { const inputNode = inputType === 'number' ? <InputNumber /> : <Input />; return ( <td {...restProps}> {editing ? ( <Form.Item name={dataIndex} style={{ margin: 0 }} rules={[ { required: true, message: `Please Input ${title}!`, }, ]} > {inputNode} </Form.Item> ) : ( children )} </td> ); }; const EditableTable = () => { const [form] = Form.useForm(); const [data, setData] = useState([ { key: '1', name: 'John Brown', age: 32, address: 'New York No. 1 Lake Park', }, { key: '2', name: 'Joe Black', age: 42, address: 'London No. 1 Lake Park', }, { key: '3', name: 'Jim Green', age: 32, address: 'Sidney No. 1 Lake Park', }, { key: '4', name: 'Jim Red', age: 32, address: 'London No. 2 Lake Park', }, ]); const [editingKey, setEditingKey] = useState(''); const isEditing = (record) => record.key === editingKey; const edit = (record) => { form.setFieldsValue({ name: '', age: '', address: '', ...record, }); setEditingKey(record.key); }; const cancel = () => { setEditingKey(''); }; const save = async (key) => { try { const row = await form.validateFields(); const newData = [...data]; const index = newData.findIndex((item) => key === item.key); if (index > -1) { const item = newData[index]; newData.splice(index, 1, { ...item, ...row }); setData(newData); setEditingKey(''); } else { newData.push(row); setData(newData); setEditingKey(''); } } catch (errInfo) { console.log('Validate Failed:', errInfo); } }; const columns = [ { title: 'Name', dataIndex: 'name', width: '25%', editable: true, }, { title: 'Age', dataIndex: 'age', width: '15%', editable: true, }, { title: 'Address', dataIndex: 'address', width: '40%', editable: true, }, { title: 'Action', dataIndex: 'action', render: (_, record) => { const editable = isEditing(record); return editable ? ( <span> <a href="javascript:;" onClick={() => save(record.key)} style={{ marginRight: 8 }} > Save </a> <Popconfirm title="Sure to cancel?" onConfirm={cancel}> <a>Cancel</a> </Popconfirm> </span> ) : ( <a disabled={editingKey !== ''} onClick={() => edit(record)}> Edit </a> ); }, }, ]; const mergedColumns = columns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: (record) => ({ record, inputType: col.dataIndex === 'age' ? 'number' : 'text', dataIndex: col.dataIndex, title: col.title, editing: isEditing(record), }), }; }); return ( <Form form={form} component={false}> <Table components={{ body: { cell: EditableCell, }, }} bordered dataSource={data} columns={mergedColumns} rowClassName="editable-row" pagination={{ onChange: cancel, }} /> </Form> ); }; export default EditableTable; ``` 这个表格组件的主要思路是: 1. 使用`useState` Hook来保存表格数据和当前正在编辑的行的key。 2. 创建一个可编辑的单元格组件`EditableCell`,根据`editing`属性来展示编辑状态或者展示状态。当编辑状态时,渲染一个`antd`的`Form.Item`,提供一个可编辑的输入。 3. 创建一个可编辑的表格组件`EditableTable`,渲染一个`antd`的`Table`组件。 4. 在表格的每一列中添加一个`editable`属性,表示该列是否可编辑。对于可编辑的列,使用`onCell`属性指定可编辑单元格的属性。 5. 在渲染表格的每一行时,根据当前行是否处于编辑状态来决定展示编辑状态还是展示状态。如果处于编辑状态,则渲染可编辑的单元格,否则渲染非可编辑的单元格。 6. 在表格中添加编辑和保存按钮,点击编辑按钮时进入编辑状态,点击保存按钮时保存修改。同时,保存和取消操作会将当前行的编辑状态取消。 这样,我们就完成了一个简单的可编辑表格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值