| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import React, { useState, useEffect } from 'react';
- import type { ModalProps } from 'antd';
- import { Modal, Form, Input, Button, message } from 'antd';
- import type { DictResult } from '../apis/dicts';
- import type { WordResult } from '../apis/words';
- import { useCreateWord, useUpdateWord } from '../apis/words';
- interface WordModalProps extends ModalProps {
- dict: DictResult;
- initialWord?: WordResult;
- refresh: () => void;
- onCancel: () => void;
- }
- const WordModal: React.FC<WordModalProps> = ({
- dict,
- initialWord,
- refresh,
- ...props
- }) => {
- const [loading, setLoading] = useState(false);
- const [form] = Form.useForm();
- useEffect(() => {
- if (props.open) {
- if (initialWord) {
- form.setFieldsValue(initialWord);
- } else {
- form.resetFields();
- }
- }
- }, [props.open, form, initialWord]);
- const createWord = useCreateWord();
- const updateWord = useUpdateWord();
- return (
- <Modal
- style={{ top: 64 }}
- title={initialWord ? '更新单词' : '创建新单词'}
- footer={null}
- destroyOnClose
- {...props}
- >
- <Form
- name="word"
- labelCol={{ span: 6 }}
- wrapperCol={{ span: 18 }}
- form={form}
- onFinish={(values: {
- value: string;
- meaning: string;
- extra?: string;
- }) =>
- void (async () => {
- try {
- setLoading(true);
- if (initialWord) {
- await updateWord({
- id: initialWord.id,
- ...values,
- star: initialWord.star,
- });
- void message.success('更新成功');
- props.onCancel();
- } else {
- await createWord({ ...values, dictID: dict.id });
- void message.success('创建成功');
- form.resetFields();
- }
- refresh();
- } catch (err) {
- if (err instanceof Error) {
- void message.error(err.message);
- }
- } finally {
- setLoading(false);
- }
- })()
- }
- >
- <Form.Item
- name="value"
- label={dict.valueTitle}
- rules={[{ required: true, message: `请输入${dict.valueTitle}` }]}
- validateTrigger="onBlur"
- >
- <Input placeholder={`请输入${dict.valueTitle}`} />
- </Form.Item>
- <Form.Item
- name="meaning"
- label={dict.meaningTitle}
- rules={[{ required: true, message: `请输入${dict.meaningTitle}` }]}
- validateTrigger="onBlur"
- >
- <Input placeholder={`请输入${dict.meaningTitle}`} />
- </Form.Item>
- {dict.extraTitle && (
- <Form.Item name="extra" label={dict.extraTitle}>
- <Input placeholder={`请输入${dict.extraTitle}`} />
- </Form.Item>
- )}
- <Form.Item label=" " colon={false}>
- <Button htmlType="submit" type="primary" loading={loading}>
- {initialWord ? '更新' : '创建'}
- </Button>
- </Form.Item>
- </Form>
- </Modal>
- );
- };
- export default WordModal;
|