loading

Ant - Form 自定义组件 form.getFiledsValue 如何获取值

import { FC, useState } from 'react';
import type { SelectProps } from 'antd';
import { Select, Space, Flex, Input, Button } from 'antd';

/**
 * 扩展选择器组件,可以通过键盘 enter 输入一个 Option
 */

const InputSelect: FC<{
  defaultOptions: SelectProps['options'];
  placeholder?: string;
  value?: any[];
  onChange?: (i: any[]) => void;
}> = (props) => {
  const [options, setOptions] = useState<SelectProps['options']>(props.defaultOptions);
  const [inputValue, setInputValue] = useState('');
  const [selectedValue, setSelectedValue] = useState(props.value);

  const handleChange = (newValue: any[]) => {
    setSelectedValue(newValue);
    if (props.onChange) {
      props.onChange(newValue);
    }
  };

  const handleAdd = () => {
    if (options) {
      setOptions([
        ...options,
        {
          label: inputValue,
          value: inputValue,
        },
      ]);
    }
  };

  return (
    <Select
      mode="multiple"
      value={selectedValue}
      style={{ width: '100%' }}
      placeholder={props.placeholder || ''}
      onChange={handleChange}
      options={options}
      dropdownRender={(menu) => {
        return (
          <>
            {menu}
            <Flex gap="middle" style={{ marginTop: '1rem' }}>
              <Input onChange={(event) => setInputValue(event.target.value)} />
              <Button onClick={handleAdd}>添加</Button>
            </Flex>
          </>
        );
      }}
      optionRender={(option) => <Space>{option.data.label}</Space>}
    />
  );
};

export default InputSelect;
posted @ 2024-04-13 17:58  Himmelbleu  阅读(2)  评论(0编辑  收藏  举报