如何向 React-Select 添加更多可搜索选项? [英] How can i add more searchable options to React-Select?
问题描述
所以我需要做的是让 react-select 的搜索形式不仅对 id 值做出反应,而且我还希望它能够搜索选择选项的同义词.
So what i need to do is have the search form of react-select not only react to id an value, but i also want it to be able to search for synonyms of the select options.
例如在度量单位列表中:
For example in a unit of measures list:
{
"id": "MIN",
"name": "minute",
"synonym": "time"
}
我希望能够输入分钟"、分钟"或时间",最后选择分钟".
I want to be able to type in "min", "minute" or "time" and end up with the selection "minute".
我尝试将另一个元素推入数组:
I tried it with pushing another element into the array:
mapUnitOfMeasure()
{
const results = [ ];
for(const c of measureUnits)
results.push({ value : c.id, label : c.name, syn: c.synonym });
}
return results
}
在我的渲染方法中,select 元素如下所示:
In my render method, the select element looks like this:
<Select
className="react-select"
placeholder=""
disabled={this.state.disabled}
value={this.state.value}
onChange={this.handleChange.bind(this)}
onBlur={this.handleBlur.bind(this)}
searchable={true}
clearable={true}
multi={false}
noResultsText={i18n.getMessage('CurrencyInput.search.form.noResults')}
options={this.mapUnitOfMeasure()} />
)
但syn"永远不会对搜索查询做出反应.
But "syn" never reacts to a search query.
有人知道我如何让它工作吗?
Anyone have an idea how i can make it work?
推荐答案
我建议您使用 filterOptions
道具,它允许您创建自己的过滤器功能.
I suggest you to use filterOptions
props that allows you to create your own filter function.
默认情况下它是这样工作的:
By default it works like this:
filterOptions={(options, filter, currentValues) => {
// Do no filtering, just return all options
return options;
}}
如果你想在 label
和 syn
中进行搜索,你可以使用这样的函数:
If you want to make a search in label
and syn
you can use the function like this:
filterOptions = (options, filterString, values) => {
return options.filter(
x => x.synonym.includes(filterString) || x.label.includes(filterString)
);
};
警告
使用 filterOptions
将覆盖 filterOption
、matchPos
、matchProp
、ignoreCase
和ignoreAccents
选项.你必须自己照顾这些道具.
Using filterOptions
will override filterOption
, matchPos
, matchProp
, ignoreCase
and ignoreAccents
options. You will have to take care of those props by yourself.
这里是一个活生生的例子.
这篇关于如何向 React-Select 添加更多可搜索选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!