【发布时间】:2021-04-08 18:42:48
【问题描述】:
为什么索引只是最后选择的索引?查看注释行中发送的索引
<Ol
width={small && "100%"}
role="listbox"
tabindex={stepIndex}
aria-activedescendant={steps[stepIndex]}
// aria-labelledby="accordion_form"
>
{steps.map((step, index) => (
<li
className={getClassName(index)}
role="option"
tabindex="0"
onKeyDown={handleSelectOnKeyDown(index)} // This index is always the same, even though I list out 1, 2 3 on the commented line underneath
onClick={() => setNextStep(step)}
id={step}
aria-selected={steps[stepIndex] === step ? "true" : "false"}
>
<span>
{index + 1}. {schema[step]?.label ?? titleizeWord(step)} // Here it is listed out 1, 2, 3 (with the added +1), so the index is correct here.
</span>
{index < stepIndex && <Icon icon={check} left="small" />}
{small && index === stepIndex && (
<Icon icon={chevron_down} left="small" />
)}
</li>
))}
</Ol>
这是句柄SelectOnKeyDown:
const handleSelectOnKeyDown = (index) => ({ keyCode }) => {
console.log("index", index);
let nextStep;
switch (keyCode) {
case KEYS.ENTER:
case KEYS.SPACE:
nextStep = steps[index];
break;
case KEYS.UP:
const upIndex = index > 0 ? index - 1 : 0;
nextStep = steps[upIndex];
break;
case KEYS.DOWN:
const maxIndex = steps?.length;
const downIndex = index < (maxIndex - 1) ? index + 1 : maxIndex;
nextStep = steps[downIndex];
break;
default:
return;
}
if (nextStep) {
setNextStep(nextStep);
}
};
我想了解可能导致此问题的原因。
【问题讨论】:
-
我想澄清一件事。我的回答目前假设您想要获取关键事件上当前焦点元素的索引(使用 tab/shift+tab)。但是在重新阅读您的问题之后,您是否期望在 JSX 中执行
index+1也会将您发送给事件处理程序的index增加 1 ?如果是这样,那将不会发生,因为您没有更改index本身,而只是使用它。让我知道这是否是问题所在,我将删除我的答案。
标签: javascript reactjs