如何使用react select without options list



我想允许用户键入单词,然后按enter/tab提交多个选项。正如本页最后一个示例(标题为"多选文本输入"(所示,此功能显然是可行的。但是,当我按下enter/tab时,值不会显示。如果我启用菜单并使用"创建新的"选项,那么它可以正常工作。此外,如果我为组件提供选项道具,效果会很好。

import CreatableSelect from 'react-select/creatable';
export type OptionType = {
value: string;
label: string;
__isNew__?: boolean;
};
export type Value = ValueType<OptionType>;
export type Values = Array<Value>;
export const createOption = (value: string, label?: string): OptionType => ({
value,
label: label ? label : value
});
interface ListTextFieldProps extends WithStyles<typeof styles>, WithTheme {
values: Values;
setValues: (values: Values) => void;
label?: string;
}

const ListTextField: React.FC<ListTextFieldProps> = props => {
const [inputValue, setInputValue] = useState('');
const selectStyles = {
input: (base: any) => ({
...base,
color: props.theme.palette.text.primary,
'& input': {
font: 'inherit'
}
})
};
const handleInputChange = (value: string, meta: InputActionMeta) => {
if (meta.action === 'input-change') {
setInputValue(value);
}
}
const handleKeyDown = (event: any) => {
if (!inputValue) return;
if (['Enter', 'Tab'].includes(event.key)) {
console.log(inputValue)
handleValueChange([...props.values, createOption(inputValue.trim())])
setInputValue('');
}
}
const handleValueChange = (values?: Value | Values | null) => {
console.log(values)
if (Array.isArray(values)) {
props.setValues(values);
} else {
throw new Error('Unexpected type passed to ReactSelect onChange handler')
}
}
return (
<div className={props.classes.root}>
<CreatableSelect
classes={props.classes}
inputValue={inputValue}
onInputChange={handleInputChange}
onKeyDown={handleKeyDown}
styles={selectStyles}
textFieldProps={{
label: props.label ? props.label : undefined,
InputLabelProps: {
shrink: true
}
}}
menuIsOpen={false}
values={props.values}
onChange={handleValueChange}
isMulti
/>
</div>
);
};

您为Select组件提供了values道具。它应该是value

最新更新