簡體   English   中英

如何在使用參考的反應js中將焦點設置為下一個輸入

[英]how to set focus to next input on enter key press in react js with refs

我在地圖中使用多個輸入,當我在 React Hooks 中單擊輸入時,我想將焦點設置為下一個輸入。 在裁判的幫助下

我正在使用材質 ui 文本字段來獲取輸入

我嘗試在沒有 ref 的情況下對 class 組件做出反應,但在鈎子中它不起作用 class 組件代碼:

constructor(props) {
this.state = {}
}

inputRefs = [];

 _handleKeyPress = e => {
        const {currentTarget} = e;
            let inputindex = this.inputRefs.indexOf(currentTarget)
            if (inputindex < this.inputRefs.length - 1) {
                this.inputRefs[inputindex + 1].focus()
            }
            else {
                this.inputRefs[0].focus()
            }
      };

內部渲染在 map function 中添加了這個

this.state.data.map((data) => return (
<TextField 
     inputProps = {{onKeyPress:(e) => this.function1(e, data)}}
     onChange={this.changevaluefunction} 
     inputRef={ref => this.inputRefs.push(ref)} 
     onFocus={this.handleFocus}  ref={`input${id}`} /> ))

我用功能組件以不同的方式實現了解決方案。 我已經采用了 4 個字段並使用createRef鈎子將其 ref 固定。

我可以從您的解決方案中看到,每當您在當前元素上按Enter鍵時,您都希望將焦點移至下一個輸入元素。

我在onKeyUp處理程序中傳遞下一個目標元素參數以及實際事件,然后檢測是否按下了Enter鍵。 如果按下Enter鍵並且存在targetElem ,那么我將焦點移動到傳遞的targetElem 通過這種方式,您可以更好地控制輸入。

你可以在這里看到我的解決方案

https://codesandbox.io/s/friendly-leftpad-2nx91?file=/src/App.js

import React, { useRef } from "react";
import TextField from "@material-ui/core/TextField";
import "./styles.css";

const inputs = [
  {
    id: "fName",
    label: "First Name"
  },
  {
    id: "lName",
    label: "Last Name"
  },
  {
    id: "gender",
    label: "Gender"
  },
  {
    id: "address",
    label: "Address"
  }
];

export default function App() {
  const myRefs = useRef([]);

  const handleKeyUp = (e, targetElem) => {
    if (e.key === "Enter" && targetElem) {
      targetElem.focus();
    }
  };

  return (
    <div>
      {inputs.map((ipt, i) => (
        <TextField
          onKeyUp={(e) =>
            handleKeyUp(e, myRefs.current[i === inputs.length - 1 ? 0 : i + 1])
          }
          inputRef={(el) => (myRefs.current[i] = el)}
          id={ipt.id}
          fullWidth
          style={{ marginBottom: 20 }}
          label={ipt.label}
          variant="outlined"
          key={ipt.id}
        />
      ))}
    </div>
  );
}

您可以將this.inputRefs轉換為 React ref,以便它通過渲染持續存在,除此之外,您幾乎可以刪除對任何this object 的所有引用。

示例組件:

const LENGTH = 10;
const clamp = (min, max, val) => Math.max(min, Math.min(val, max));

export default function App() {
  const [data] = useState([...Array(LENGTH).keys()]);

  const inputRefs = useRef([]); // <-- ref to hold input refs

  const handleKeyPress = index => () => {                   // <-- enclose in scope
    const nextIndex = clamp(0, data.length - 1, index + 1); // <-- get next index
    inputRefs.current[nextIndex].focus();                   // <-- get ref and focus
  };

  return (
    <div className="App">
      {data.map((data, index) => (
        <div key={index}>
          <TextField
            inputProps={{ onKeyPress: handleKeyPress(index) }}   // <-- pass index
            inputRef={(ref) => (inputRefs.current[index] = ref)} // <-- save input ref
          />
        </div>
      ))}
    </div>
  );
}

編輯 how-to-set-focus-to-next-input-on-enter-key-press-in-react-js-with-refs

如果是映射輸入字段,想重點點擊,可以直接給輸入賦予id屬性,傳入數組id。

之后,您可以將 function 中的 id 作為參數傳遞,並通過document.getElementById(id).focus()

暫無
暫無

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

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