WordDrawer.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import React from 'react';
  2. import { Drawer, Form, Input, Button, message } from 'antd';
  3. import type { DrawerProps } from 'antd';
  4. import type { WordResult } from '../apis/words';
  5. import { useCreateWord, useUpdateWord } from '../apis/words';
  6. interface WordDrawerProps extends DrawerProps {
  7. dictID: number;
  8. initialWord?: WordResult;
  9. refresh: () => void;
  10. onClose: () => void;
  11. }
  12. const WordDrawer: React.FC<WordDrawerProps> = ({
  13. dictID,
  14. initialWord,
  15. refresh,
  16. ...props
  17. }) => {
  18. const createWord = useCreateWord();
  19. const updateWord = useUpdateWord();
  20. return (
  21. <Drawer
  22. title={initialWord ? '更新单词' : '创建新单词'}
  23. destroyOnClose
  24. {...props}
  25. >
  26. <Form
  27. name="word"
  28. labelCol={{ span: 6 }}
  29. wrapperCol={{ span: 18 }}
  30. initialValues={initialWord}
  31. onFinish={(values: { value: string; meaning: string; extra: string }) =>
  32. void (async () => {
  33. try {
  34. if (initialWord) {
  35. await updateWord({ ...initialWord, ...values });
  36. void message.success('更新成功');
  37. } else {
  38. await createWord({ ...values, dictID });
  39. void message.success('创建成功');
  40. }
  41. refresh();
  42. props.onClose();
  43. } catch (err) {
  44. if (err instanceof Error) {
  45. void message.error(err.message);
  46. }
  47. }
  48. })()
  49. }
  50. >
  51. <Form.Item
  52. label="单词"
  53. name="value"
  54. rules={[{ required: true, message: '请输入单词' }]}
  55. validateTrigger="onBlur"
  56. >
  57. <Input placeholder="请输入单词(如:good)" />
  58. </Form.Item>
  59. <Form.Item
  60. label="词义"
  61. name="meaning"
  62. rules={[{ required: true, message: '请输入词义' }]}
  63. validateTrigger="onBlur"
  64. >
  65. <Input placeholder="请输入词义(如:好的)" />
  66. </Form.Item>
  67. <Form.Item label="附加" name="extra">
  68. <Input placeholder="请输入附加(如:[ɡʊd])" />
  69. </Form.Item>
  70. <Form.Item label=" " colon={false}>
  71. <Button htmlType="submit" type="primary">
  72. {initialWord ? '更新' : '创建'}
  73. </Button>
  74. </Form.Item>
  75. </Form>
  76. </Drawer>
  77. );
  78. };
  79. export default WordDrawer;