Select.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import {filterOptions} from '@utils';
  2. import css from './index.module.css';
  3. import {Row, Col, Select} from 'antd';
  4. import classNames from 'classnames';
  5. import {FC} from 'react';
  6. import {Controller, UseControllerProps} from 'react-hook-form';
  7. type Props = {
  8. label: string;
  9. placeholder?: string;
  10. width?: string;
  11. data: {value: string, label: string}[];
  12. required?: boolean;
  13. showSearch?: boolean;
  14. } & UseControllerProps<any, any>;
  15. const ModalSelect: FC<Props> = function({
  16. control,
  17. name,
  18. label,
  19. placeholder,
  20. data,
  21. required,
  22. showSearch,
  23. }) {
  24. return (
  25. <Row className='full-width' gutter={12}>
  26. <Col span={6} offset={2}>
  27. <label
  28. className={
  29. classNames([
  30. css.textRight,
  31. {[css.fieldRequired]: required ?? true},
  32. ])
  33. }
  34. htmlFor={`operation_${name}`}
  35. >
  36. {label}
  37. </label>
  38. </Col>
  39. <Col span={12}>
  40. <Controller
  41. name={name}
  42. control={control}
  43. render={function({field: {value, onChange, ref}, formState: {errors}}) {
  44. const errorTips = errors[name]?.message?.toString() ?? '';
  45. return (
  46. <>
  47. <Select
  48. showSearch={showSearch}
  49. rootClassName={classNames([css.modalSelect, css.filedWidth])}
  50. data-testid={`select_${name}`}
  51. defaultActiveFirstOption={false}
  52. filterOption={showSearch ? filterOptions : false}
  53. placeholder={placeholder ?? '请选择'}
  54. id={`operation_${name}`}
  55. // 处理placeholder不显示问题
  56. value={value.length ? value : void 0}
  57. onChange={onChange}
  58. ref={ref}
  59. options={data}
  60. className='width-full'
  61. getPopupContainer={(node: HTMLElement) => node.parentNode as HTMLElement}
  62. />
  63. <p className={classNames([css.errorTips, {[css.errorTipsHidden]: !errorTips}])}>
  64. {errorTips}
  65. </p>
  66. </>
  67. );
  68. }}
  69. />
  70. </Col>
  71. </Row>
  72. );
  73. };
  74. export default ModalSelect;