RecommendQuestions.tsx 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
  2. import { Button, Form, Input, Switch } from 'antd';
  3. import cls from 'classnames';
  4. import React, { useEffect } from 'react';
  5. import { useTranslation } from 'react-i18next';
  6. import styles from '../styles.module.css';
  7. interface RecommendQuestion {
  8. question: string;
  9. valid: boolean;
  10. }
  11. interface FormRecommendQuestion {
  12. recommend_questions: RecommendQuestion[];
  13. }
  14. const RecommendQuestions: React.FC<{
  15. initValue: any[];
  16. updateData: (data: RecommendQuestion[]) => void;
  17. classNames?: string;
  18. formStyle?: string;
  19. labelCol?: boolean;
  20. }> = ({ initValue, updateData, classNames, formStyle, labelCol = true }) => {
  21. const { t } = useTranslation();
  22. const [form] = Form.useForm<FormRecommendQuestion>();
  23. const recommendQuestions = Form.useWatch('recommend_questions', form);
  24. // 将数据实时返回给消费组件
  25. useEffect(() => {
  26. updateData(recommendQuestions?.filter(question => !!question.question));
  27. }, [recommendQuestions, updateData]);
  28. return (
  29. <div className={cls(styles['recommend-questions-container'], classNames)}>
  30. <Form<FormRecommendQuestion>
  31. style={{ width: '100%' }}
  32. form={form}
  33. initialValues={{
  34. recommend_questions: initValue || [{ question: '', valid: false }],
  35. }}
  36. autoComplete='off'
  37. wrapperCol={{ span: 20 }}
  38. {...(labelCol && { labelCol: { span: 4 } })}
  39. >
  40. <Form.Item label={t('recommended_questions')}>
  41. <Form.List name='recommend_questions'>
  42. {(fields, { add, remove }) => (
  43. <>
  44. {fields.map(({ key, name }, index) => (
  45. <div key={key} className={cls('flex flex-1 items-center gap-8 mb-6', formStyle)}>
  46. <Form.Item label={`${t('question')} ${index + 1}`} name={[name, 'question']} className='grow'>
  47. <Input placeholder={t('please_input_recommended_questions')} />
  48. </Form.Item>
  49. <Form.Item label={t('is_effective')} name={[name, 'valid']}>
  50. <Switch
  51. style={{
  52. background: recommendQuestions?.[index]?.valid ? '#1677ff' : '#ccc',
  53. }}
  54. />
  55. </Form.Item>
  56. <Form.Item>
  57. <MinusCircleOutlined
  58. onClick={() => {
  59. remove(name);
  60. }}
  61. />
  62. </Form.Item>
  63. </div>
  64. ))}
  65. <Form.Item className={cls(formStyle)}>
  66. <Button
  67. type='dashed'
  68. onClick={() => {
  69. add({ question: '', valid: false });
  70. }}
  71. block
  72. icon={<PlusOutlined />}
  73. >
  74. {t('add_question')}
  75. </Button>
  76. </Form.Item>
  77. </>
  78. )}
  79. </Form.List>
  80. </Form.Item>
  81. </Form>
  82. </div>
  83. );
  84. };
  85. export default RecommendQuestions;