【问题标题】:Index from .map is not expected.map 中的索引不是预期的
【发布时间】: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


【解决方案1】:

我认为您的实现需要从 onKeyDown 更改为 onKeyUp。我假设这是因为当从一个 li 项目导航到另一个项目时,您的事件将在 keydown 上发生,但您的新焦点元素将是控制台中登录内容之前或之后的一个索引(这发生在 keydown 上)。

简而言之,keydown 会在你离开当前元素时执行,keyup 会在你到达它时执行。

再次谈到离开和到达时,它使用的是Tab/Shift+Tab导航键。对于其他不执行导航的键,index 值将与所关注的内容一致,无论是使用 keydown 还是 keyup。

试试下面的沙盒:-

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2022-11-22
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多