Select.tsx 2.2 KB

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