使用逗号在 #react 选择上创建新标记



1.3.0版上,每次用户按下键 "," react-select 都会创建一个新标签,这很有用,因为在实现这个库之前,我们有用户通过按 Enter 将标签作为单个字符串而不是多个字符串引入的情况。

不幸的是,在重构 2.0之后,我找不到任何方法来执行此操作,有什么方法可以配置此行为吗?

  • 版本 1.3.0 上的示例
  • 最新版本的示例

您需要自定义一些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或创建新标签。

最新更新