我正在尝试做一个输入,允许用户选择多个项目。选择完成后,他可以按Enter将选择的内容推入状态中的数组中。然后,输入将清除,并为他的下一组选择做好准备。(想象一下快速填充一个二维数组)。但是,使用下面的代码,如果用户按Enter选择提示,我的回调pushToState将像在onKeyDown中一样触发。实现此行为的正确方法是什么?
<Typeahead
id="basic-typeahead-multiple"
labelKey="name"
multiple
onChange={setMultiSelections}
options={options}
selected={multiSelections}
onKeyDown={(event) => {
if (event.key === 'Enter') {
pushToState(multiSelections);
setMultiSelections([]);
}
}}
/>发布于 2020-08-23 03:51:54
您的用例类似于the one in this question。您基本上需要确定用户是否正在选择菜单项。可以通过检查typeahead的activeIndex来做到这一点:
// Track the index of the highlighted menu item.
const [activeIndex, setActiveIndex] = useState(-1);
const onKeyDown = useCallback(
(e) => {
// Check whether the 'enter' key was pressed, and also make sure that
// no menu items are highlighted.
if (event.key === 'Enter' && activeIndex === -1) {
pushToState(multiSelections);
setMultiSelections([]);
}
},
[activeIndex]
);
return (
<Typeahead
id="basic-typeahead-multiple"
labelKey="name"
multiple
onChange={setMultiSelections}
options={options}
onChange={setMultiSelections}
onKeyDown={onKeyDown}
selected={multiSelections} >
{(state) => {
// Passing a child render function to the component exposes partial
// internal state, including the index of the highlighted menu item.
setActiveIndex(state.activeIndex);
}}
</Typeahead>
);https://stackoverflow.com/questions/63529327
复制相似问题