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;
标签:const,form,getFiledsValue,value,useState,props,import,newValue,自定义
From: https://www.cnblogs.com/Himmelbleu/p/18133160