React JS - 元素专注于输入不起作用

React JS - element focus on input not working

我在以编程方式聚焦元素时遇到问题。 我有一个 ul 看起来像这样:

      <ul className="text-left">
        {Object.keys(props.characters).map((char, i) => {
          return (
            <li key={props.characters[char].key}>
              <button type="button" className={"btn align-middle bg_" + props.characters[char].character}>
                <div className={"label text-left float-left " + getFontColorFromCharacter(props.characters[char].character)}>
                  <img alt="" className="char-img" src={"/images/characters/" + props.characters[char].character + "_xs.png"}/>
                  <input className="align-middle d-none" id={props.characters[char].key + "_input"} type="text" placeholder="Nom joueur" value={props.characters[char].player_name} onChange={e => props.changePlayerNameHandler(props.characters[char],e)} onBlur={e => toggleDNone(props.characters[char].key)} onKeyDown={e => tabToNext(e)}/>
                  <span className="align-middle" id={props.characters[char].key + "_span"} onClick={e => toggleDNone(props.characters[char].key)} > {props.characters[char].player_name}</span>
                </div>
                <div className={"actions " + getFontColorFromCharacter(props.characters[char].character)}>
                  <span className="action">
                    <FontAwesomeIcon icon="times-circle" title="Supprimer" onClick={() => props.removeCharacterHandler(props.characters[char].key)}/>
                  </span>
                </div>
              </button>
            </li>
          );
        })}
      </ul>

Javascript :

//Toggle d-none class on input & span for player name edition
function toggleDNone(key) {
    document.getElementById(key + "_input").classList.toggle("d-none");
    document.getElementById(key + "_span").classList.toggle("d-none");

    if (!document.getElementById(key + "_input").classList.contains("d-none")) {
        document.getElementById(key + "_input").focus();
    }
}

//When the user hit tab key, navigate to next input
function tabToNext(event){
    if(event.key === "Tab")
    {
        var allInput = document.querySelectorAll("[id$='_input']");

        var indexOfCurrent = Array.from(allInput).indexOf(event.target);
        var id;
        if (indexOfCurrent + 1 === Array.from(allInput).length)
        {
            id = allInput[0].id;
        }
        else
        {
            id = allInput[indexOfCurrent + 1].id;
        }

        toggleDNone(allInput[indexOfCurrent].id.replace("_input", ""));
        toggleDNone(id.replace("_input",""));
    }
}

当用户点击 span 时,显示输入并且焦点起作用。当用户按下 Tab 键进入下一个输入时,显示输入但焦点不起作用。

我尝试将 tabIndex 设置为 -1,就像我在 post 上看到的那样,但它没有用。

有什么想法吗?

找到解决方案。 问题是第二个 toggleDNone 调用在第一个调用完成之前就开始了。

我刚刚在第二次调用时添加了 100 毫秒的 setTimeOut,它起作用了。

谢谢大家