【问题标题】:First input autofocus for OTP input fields in ReactReact 中 OTP 输入字段的第一个输入自动对焦
【发布时间】:2022-08-16 18:46:11
【问题描述】:

我在 React You can see this image 中进行了 OTP 输入。一行是一个输入,我有 6 个输入。输入工作没有问题。我需要当组件打开时,第一个输入必须是自动对焦。当我使用<input autofocus/> 时,最后一个输入是自动对焦,我需要第一个输入。

我的父组件

  const [code, setcode] = useState(new Array(6).fill(\"\"));

一次性密码组件

 <div className=\"digit-inputs\">
        {props.code.map((data, index) => {
          return (
            <input
              disabled={props.second <= 0 ? true : false}
              type=\"text\"
              className=\"otp-field\"
              name=\"otp\"
              maxLength={1}
              key={index}
              style={data ? { borderBottom: \"3px solid #7dbf2a\" } : { borderBottom: \"3px solid grey\" }}
              value={data}
              onChange={(e) => handleChange(e.target, index)}
              onFocus={(e) => e.target.select}
            />
          );
        })}
      </div>

我的功能

  const handleChange = (element, index) => {
    if (isNaN(element.value)) return false;

    props.setcode([...props.code.map((d, indx) => (indx === index ? element.value : d))]);

    //Focus next input

    if (element.nextSibling) {
      element.nextSibling.focus();
    }
  };

    标签: javascript arrays reactjs


    【解决方案1】:

    如果您只想在组件挂载时获得焦点,则可以使用数组的索引。只需添加autoFocus={index === 0}

             <input
              type="text"
              className="otp-field"
              name="otp"
              maxLength={1}
              key={index}
              style={
                data
                  ? { borderBottom: "3px solid #7dbf2a" }
                  : { borderBottom: "3px solid grey" }
              }
              //value={data}
              onFocus={(e) => e.target.select}
              autoFocus={index === 0} // add this line
              //onChange
            />
    

    【讨论】:

      【解决方案2】:

      您还可以使用 npm 包来解决您的问题,因为在使用输入标签时您可能会错过很多边缘情况。随意使用https://www.npmjs.com/package/react18-input-otp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-04
        • 2020-06-03
        • 2020-02-07
        • 2018-08-17
        • 1970-01-01
        相关资源
        最近更新 更多