如何在 react-select 到达底部时防止 ArrowDown?
How to prevent ArrowDown when reached bottom in react-select?
在反应中-select,
当在最后一个选项上按下 ArrowDown 时,焦点将转到第一个选项。
然后在第一个选项上按 ArrowUp,焦点将转到最后一个选项。
如何预防?
我应该为此制作自己的 MenuList
吗?
我真的只想阻止这种行为,因为当焦点到达最后一个选项时,我会从服务器获取更多选项。
恐怕docs中没有API做这样的事情。一种可能的解决方案是:
- 通过收听
focus
事件来跟踪您当前的焦点指数。
- 拦截
keydown
事件并根据当前焦点索引和options.length
有条件地停止击键。 注意 keydown
事件在 focus
事件之前触发。
export function MySelect() {
const focusIndexRef = useRef(-1);
return (
<Select
options={options}
ariaLiveMessages={{
onFocus: (e) => {
focusIndexRef.current = e.options.indexOf(e.focused);
}
}}
onKeyDown={(e) => {
if (e.key === "ArrowDown" && focusIndexRef.current === options.length - 1) {
e.preventDefault();
}
if (e.key === "ArrowUp" && focusIndexRef.current === 0) {
e.preventDefault();
}
}}
/>
);
}
现场演示
在反应中-select,
当在最后一个选项上按下 ArrowDown 时,焦点将转到第一个选项。 然后在第一个选项上按 ArrowUp,焦点将转到最后一个选项。
如何预防?
我应该为此制作自己的 MenuList
吗?
我真的只想阻止这种行为,因为当焦点到达最后一个选项时,我会从服务器获取更多选项。
恐怕docs中没有API做这样的事情。一种可能的解决方案是:
- 通过收听
focus
事件来跟踪您当前的焦点指数。 - 拦截
keydown
事件并根据当前焦点索引和options.length
有条件地停止击键。 注意keydown
事件在focus
事件之前触发。
export function MySelect() {
const focusIndexRef = useRef(-1);
return (
<Select
options={options}
ariaLiveMessages={{
onFocus: (e) => {
focusIndexRef.current = e.options.indexOf(e.focused);
}
}}
onKeyDown={(e) => {
if (e.key === "ArrowDown" && focusIndexRef.current === options.length - 1) {
e.preventDefault();
}
if (e.key === "ArrowUp" && focusIndexRef.current === 0) {
e.preventDefault();
}
}}
/>
);
}