Вам нужно будет настроить немного react-select
, чтобы достичь того, что вы хотите.
В основном это то, что я закончил:
import React, { Component } from "react";
import CreatableSelect from "react-select/lib/Creatable";
type State = {
options: [{ [string]: string }],
value: string | void
};
const createOption = (label: string) => ({
label,
value: label.toLowerCase().replace(/\W/g, "")
});
const defaultOptions = [
createOption("One"),
createOption("Two"),
createOption("Three")
];
export default class CreatableAdvanced extends Component<*, State> {
state = {
inputValue: "",
options: defaultOptions,
value: []
};
onKeyDown = e => {
if (e.keyCode === 188) {
e.preventDefault();
if (this.state.inputValue !== "") {
this.handleCreate(this.selectRef.state.inputValue.slice(0, -1));
}
} else {
this.setState({ inputValue: this.state.inputValue + e.key });
}
};
handleChange = (newValue: any, actionMeta: any) => {
this.setState({ value: newValue });
};
handleCreate = (inputValue: any) => {
const { options, value } = this.state;
const newOption = createOption(inputValue);
this.setState({
inputValue: "",
options: [...options, newOption],
value: [...value, newOption]
});
};
render() {
const { isLoading, options, value } = this.state;
return (
<CreatableSelect
ref={r => (this.selectRef = r)}
isClearable
isMulti
isDisabled={isLoading}
isLoading={isLoading}
inputValue={this.state.inputValue}
onKeyDown={this.onKeyDown}
onChange={this.handleChange}
onCreateOption={this.handleCreate}
options={options}
value={value}
/>
);
}
}
Здесь живой пример того, что вы хотите.
Идея состоит в том, чтобы обойти нативный inputValue
выбора и передать свой собственный.С функцией onKeyDown
вы можете либо заполнить inputValue
, либо создать новый тег.