Better Modal

一个帮助简化 antd Modal 状态管理的工具

安装

pnpm add @cicara/better-modal

使用方式

  1. 以常规方式创建 Antd 模态,唯一不同的是使用 useModalContext 自动管理Modal的状态。

    import { Input, Modal } from "antd";
    import { useModalContext } from "@cicara/better-modal";
    import { Form } from "antd";
    import { useCallback, useEffect } from "react";
    
    export type MyModalProps = {
      value?: string;
    };
    
    export function MyModal(props: MyModalProps) {
      const modal = useModalContext<string>(); // <- First use modal context
    
      const [form] = Form.useForm();
    
      const handleSubmit = useCallback(
        (values: { name: string }) => {
          modal.resolve(values.name); // <- Close the modal and return the data or message
        },
        [modal.resolve]
      );
    
      useEffect(() => {
        if (!modal.visible) {
          return;
        }
        form.setFieldsValue({ name: props.value });
      }, [props.value]);
    
      return (
        <Modal
          open={modal.visible}
          title="What's your name?"
          onOk={() => form.submit()}
          onCancel={() => modal.reject(new Error("user cancel"))} // <- Close modal with reject and reason
          afterClose={modal.destroy} // Optional, destroy the modal
        >
          <Form form={form} onFinish={handleSubmit} autoComplete="off">
            <Form.Item name="name" rules={[{ required: true }]}>
              <Input placeholder="your name..." />
            </Form.Item>
          </Form>
        </Modal>
      );
    }
  2. 使用 useModal<string>(MyModal) React Hook 创建 Modal,并在合适的位置插入 {myModal.placeholder} 以便 Modal 能正确获取上下文。

    import { useModal } from "@cicara/better-modal";
    import { MyModal } from "./my-modal";
    
    export function App() {
      const myModal = useModal(MyModal);
    
      return <div>{myModal.placeholder}</div>;
    }
  3. 使用myModal.show函数显示 Modal 并传递参数,show函数返回一个 Promise,它对应于useModalContext中的resolvereject函数。

    import { Button } from "antd";
    import { useModal } from "@cicara/better-modal";
    import { MyModal } from "./my-modal";
    import { useCallback } from "react";
    
    export function App() {
      const myModal = useModal(MyModal);
    
      const handleOpenModal = useCallback(async () => {
        try {
          const result = await myModal.show<string>({ value: "hungtcs" });
          alert(result);
        } catch (err) {
          alert(err);
        }
      }, []);
    
      return (
        <div>
          <Button onClick={handleOpenModal}>Open Modal</Button>
          {myModal.placeholder}
        </div>
      );
    }

鸿则
2.6k 声望15 粉丝