簡體   English   中英

為什么 useRef 焦點在 React 中不起作用?

[英]Why is useRef focus not working in React?

在 React 中,我希望如果在一個表單中輸入內容,另一個表單會立即設置為焦點。

例如:

 <html> <head> <title>React App</title> <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> </head> <body> <div id="mydiv"></div> <script type="text/babel"> //Now its basically like React function Inputs() { const [otp, setOtp] = React.useState([]); //Here are stored the Values of the numbers const itemsRef = React.useRef([]); //Here are stored the refs of the numbers const setOtpfunction = (e, i) => { const key = parseInt(e.key); //I first parse the key that i got from onKeyPress to a number if (key) { let OTP = [...otp]; OTP[i] = key; setOtp(OTP); //Then i update the numbers if (i < 5) { const nextForm = i + 1; //Here i say that the next item schould be the item with the index + 1 ref[i].focus(); //And here i set the focus. ref.current.focus() wouldnt work in this case } } }; return ( <div className="space-x-2"> <input placeholder="first input" type="number" className="otpNumber" onChange={(e) => (e = null)} //that there is no error because there is no onChange function required onKeyPress={(e) => setOtpfunction(e, 0)} ref={(ref) => (itemsRef[0] = ref)} autoFocus value={otp[0] || ""} /> <input placeholder="second input" type="number" className="otpNumber" onChange={(e) => (e = null)} //that there is no error because there is no onChange function onKeyPress={(e) => setOtpfunction(e, 1)} ref={(ref) => (itemsRef[1] = ref)} value={otp[1] || ""} /> <input placeholder="third input" type="number" className="otpNumber" onChange={(e) => (e = null)} //that there is no error because there is no onChange function onKeyPress={(e) => setOtpfunction(e, 2)} ref={(ref) => (itemsRef[2] = ref)} value={otp[2] || ""} /> <p>Now you can type in 1 number in the inputs and they are stored in UseState. But i want that if in the first input, one number is entered, it focuses the second input and so on</p> </div> ); } class Render extends React.Component { render() { return ( <div> <Inputs /> </div> ); } } ReactDOM.render(<Render />, document.getElementById("mydiv")); </script> </body> </html>

控制台的錯誤只是警告您應該為生產編譯腳本。 這就是我隱藏它的原因。

我還使用 document.getElemntbyId 對其進行了測試,但也沒有用。

我希望你能明白我的意思。 感謝您提供的任何答案!

我寧願制作一個Input組件,當用戶鍵入內容並相應地更新 state 時通知父組件:

const OTP_LENGTH = 4;

export default function OTPForm() {
  const [index, setIndex] = useState(0);

  function done() {
    if (index === OTP_LENGTH - 1) {
      console.log("All inputs filled");
      return;
    }
    setIndex(index + 1);
  }

  return (
    <form>
      {Array.from({ length: OTP_LENGTH }, (_, i) => (
        <Input key={i} isCurrent={i === index} done={done} />
      ))}
    </form>
  );
}

function Input({ isCurrent, done }) {
  const ref = useRef(null);

  useEffect(() => {
    if (isCurrent && ref.current) {
      ref.current.focus();
    }
  }, [isCurrent]);

  function onInput(event) {
    if (event.target.value > 1) {
      event.preventDefault();
      return;
    }
    if (event.target.value === 1) {
      done();
    }
  }

  return <input ref={ref} onInput={onInput} type="number"/>;
}

由您決定從父組件公開適當的onError / onSubmit處理程序。

暫無
暫無

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

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