use*_*own 6 javascript reactjs react-select redux-form
我正在尝试使用react-select 创建一个选择元素,并为此使用Creatable 组件。
在我当前的实现中,它不会提示用户输入“创建”选项,如文档所示,它将 显示默认的“无选项”。
我也在使用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}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
编辑:
我还尝试从文档中导入makeCreatableSelect 但没有帮助:
import Creatable, { makeCreatableSelect } from 'react-select/creatable';
<Creatable
//here goes props
/>
Run Code Online (Sandbox Code Playgroud)
我认为你的问题来自于你的自定义过滤器实现
这有点棘手,因为从文档中看,没有带有自定义过滤器实现的 CreatableSelect 示例。
为了解决这个问题,您的自定义过滤器必须重新运行"undefined",以便“告诉”<CreatableSelect />组件没有这样的选项。
所以这是实现这一目标的一种选择:
const customFilter = (option, searchText) => {
return option.data.searchfield !== undefined ? option.data.searchfield.toLowerCase().includes(searchText.toLowerCase())
: "undefined"
};
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您的 CreatableSelect 将知道是否找到该值
我在代码中注意到的另一个问题是,renderValue当找不到匹配的选项时,您的方法将返回空字符串...不好:如果您希望用户创建选项,则必须在创建选项时呈现它。 ..不是空字符串。
因此,将其替换为以下内容:
const renderValue = (value) => {
const val = value === "" ?
null :
options.find((obj) => obj.value === input.value);
return val || {value : value, label: value};
};
Run Code Online (Sandbox Code Playgroud)
这将创造你的新选择。当然,您可以根据自己的逻辑更改标签。
| 归档时间: |
|
| 查看次数: |
10228 次 |
| 最近记录: |