我正在尝试使用 react-select 创建一个选择元素,并为此使用了 Createable 组件。
在我当前的实现中,它不会在输入时提示用户输入“创建”选项,如 documentation 所示。
它将显示默认的“无选项”。
我也在使用redux-form
图书馆,但我认为问题不在于那里。
到目前为止,这是我的代码:
import Select from "react-select/creatable";
import React from "react";
const customFilter = (option, searchText) => {
return option.data.searchfield.toLowerCase().includes(searchText.toLowerCase());
};
export default (props) => {
const { input, options, placeholder } = props;
const renderValue = (value) => {
const val =
value === "" ? null : options.find((obj) => obj.value === input.value);
return val || "";
};
return (
<Select
value={renderValue(input.value)}
name={input.name}
onFocus={() => input.onFocus(input.value)}
onChange={(value) => input.onChange(value.value)}
onBlur={() => input.onBlur(input.value)}
options={options}
isRtl={true}
placeholder={placeholder}
filterOption={customFilter}
/>
);
};
编辑 :我还尝试从文档中导入
makeCreatableSelect
但它没有帮助: import Creatable, { makeCreatableSelect } from 'react-select/creatable';
<Creatable
//here goes props
/>
最佳答案
我认为您的问题来自您的自定义过滤器实现
这有点棘手,因为从文档中没有 CreatableSelect 的示例与自定义过滤器的实现。
要解决这个问题,您的自定义过滤器必须重新运行 "undefined"
为了“告诉”<CreatableSelect />
组件没有这样的选项。
所以这是实现这一目标的一种选择:
const customFilter = (option, searchText) => {
return option.data.searchfield !== undefined ? option.data.searchfield.toLowerCase().includes(searchText.toLowerCase())
: "undefined"
};
这样,您的 CreatableSelect 将知道是否找到了该值我在您的代码中注意到的另一个问题是您的
renderValue
方法将在找不到匹配选项时返回一个空字符串...不好:如果您希望用户创建选项,则必须在创建选项时呈现它...不是空字符串。所以用类似的东西替换它:
const renderValue = (value) => {
const val = value === "" ?
null :
options.find((obj) => obj.value === input.value);
return val || {value : value, label: value};
};
这将创建您的新选项。当然,您可以根据自己的逻辑更改标签。
关于javascript - react 选择可创建的 "no options"而不是 "create",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62743712/