我正在从
Dropdown
渲染一个 semantic-ui-react
组件。当我设置 searchQuery
属性时,所选选项的显示文本无法正确显示。相反,它始终显示最新的查询。我尝试根据所选值显式设置 text
属性,但它仍然只显示最近的查询。如何使用 searchQuery
属性而不破坏显示文本?
这段代码演示了这个问题。删除
query
、setQuery
、searchQuery
、onSearchChange
和 text
,看看它在没有 searchQuery
属性的情况下如何工作(如预期)。
import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'
const countryOptions = [
{ key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
{ key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
{ key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]
const DropdownExampleSearchSelection = () => {
const [value, setValue] = useState(null);
const [query, setQuery] = useState('');
const text = countryOptions.find(o => o.value === value)?.text;
return (
<div>
<p>value: {value}</p>
<p>text: {text}</p>
<Dropdown
placeholder='Select Country'
fluid
search
selection
options={countryOptions}
searchQuery={query}
onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
value={value}
onChange={(e, { value }) => setValue(value)}
text={text}
/>
</div>
);
}
export default DropdownExampleSearchSelection
如果我在用户做出选择时清除查询,它似乎可以工作。不需要
text
道具。
onChange={(e, { value }) => {
setQuery(undefined);
setValue(value);
}}
完整的工作示例:
import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'
const countryOptions = [
{ key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
{ key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
{ key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]
const DropdownExampleSearchSelection = () => {
const [value, setValue] = useState(null);
const [query, setQuery] = useState('');
return (
<Dropdown
placeholder='Select Country'
fluid
search
selection
options={countryOptions}
searchQuery={query}
onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
value={value}
onChange={(e, { value }) => {
setQuery('');
setValue(value);
}}
/>
);
}
export default DropdownExampleSearchSelection