簡體   English   中英

將焦點切換到 React 中的下一個輸入字段

[英]Switching focus to the next input field in React

在我的反應應用程序中,有一個輸入驗證碼的部分。 它看起來像這樣:在此處輸入圖像描述

我希望在輸入下一個數字時焦點自動切換到下一個數字輸入字段。 現在我正在使用 DOM 操作,但我想找到一個更強大的解決方案。

我現在的代碼: https://codesandbox.io/s/fast-shadow-vqojs2?file=/src/App.js

我看到了使用 Ref 解決問題的選項。 但以我的拙見,添加 5 個 refs 也不是很好。 請提供一些建議

ref是這里的解決方案

沙盒

聲明參考:

const itemsRef = useRef([]);

添加輸入的參考

<input
  ref={(ref) => itemsRef.current.push(ref)}
  name={`code-${index}`}
  key={index}
  style={{ width: "20px", height: "20px" }}
  onChange={(event) => codeChangeHandler(event)}
  maxLength={1}
/>

關注下一個參考:

itemsRef.current[fieldIntIndex + 1].focus();

對於您的情況,如果inputs是兄弟,您可以輕松檢查當前輸入是否有nextElementSibling ,如果,則關注它,如果不是(列表中的最后一個輸入),則模糊

const codeChangeHandler = (event) => {
    const element = event.target;
    const nextSibling = element.nextElementSibling;
    nextSibling ? nextSibling.focus() : element.blur();
};

這是一個工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM