这是我在 FormField 中使用服务器端搜索的 Select 组件的基本实现:
export default function AddProduct() {
const [form, setForm] = useState({ category_id: '' })
const [categories, setCategories] = useState([])
const onSearch = string => {
const makeRequest = async () => {
const term = string && string.length ? string.trim() : ''
const options = { q: term, 'per-page': 1 }
// Requesting categories based on user's search.
const res = await API().categories.fetchMany(options)
try {
const json = await res.json()
// Updating the categories list on-the-fly from server-side response.
setCategories(json.data)
} catch (e) {
// ...
}
}
makeRequest()
}
return (
<Box>
<Form
value={form}
onChange={nextForm => setForm(nextForm)}
>
<FormField
name='category_id'
htmlFor='input-categories'
label='Categories'
>
<Select
name='category_id'
// Dispatches the first request (usability only) in order to prevent
// user from viewing an empty list.
onOpen={onSearch}
onSearch={onSearch}
// Options are always the filtered list from server-side.
options={categories}
labelKey="name"
valueKey={{ key: 'id', reduce: true }}
/>
</FormField>
</Form>
</Box>
)
}
预期行为
I expected users to search & select options indefinitely without selected option becoming blank when it's not present in the options array.
实际行为
如果用户搜索一个类别并选择,那么它会正确显示为选定的选项,但是当用户再次搜索并且选定的选项没有出现在服务器端结果中(换句话说,不在选项列表中)时,那么选定的选项变为空白。
1. 在这里,我有意在每次搜索时只呈现一个结果。
2.首先,我选择“Tijolo”类别。
3. 然后我换成“Ferro”。
4. 最后一步我再次打开选择下拉菜单,它调度请求“onOpen”事件,结果页面中不存在“Ferro”,然后它的选项变为空白。
正如我现在所看到的,“onSearch”事件似乎不会使其空白,但“onOpen”会。我想知道为什么(?)。
有谁知道如何处理“onOpen”和“onSearch”事件在索环选择组件中呈现动态选项?
索环版本:2.17.2