You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中Uncaught ReferenceError: input1Ref未定义问题的解决方法

解决React输入框自动聚焦时的Ref未定义错误

错误原因

Uncaught ReferenceError: input1Ref is not defined 本质是变量和hooks的作用域错误——React要求所有hooks(useRef、useState)必须在函数组件的顶层作用域内调用,相关变量也得在组件内部声明,否则组件内的事件函数和JSX无法访问这些变量。

修复后的完整代码

import React, { useRef, useState } from "react";

const OTPVerification = () => {
  // 初始值用空字符串,适配验证码输入场景
  const [OTPInput, setOTPInput] = useState(["", "", "", ""]);
  const input1Ref = useRef(null);
  const input2Ref = useRef(null);

  const handleChangeInput1 = (e) => {
    // 函数式更新state,避免闭包导致的状态不同步问题
    setOTPInput(prev => [e.target.value, prev[1], prev[2], prev[3]]);

    // 输入非空时聚焦第二个输入框,用可选链避免null报错
    if (e.target.value.trim() !== "") {
      input2Ref.current?.focus();
    }
  };

  const handleChangeInput2 = (e) => {
    setOTPInput(prev => [prev[0], e.target.value, prev[2], prev[3]]);
  };

  return (
    <>
      <div className="otp-verification-inputs">
        <input
          placeholder=""
          type="tel"
          maxLength="1"
          name="otpValue1"
          ref={input1Ref}
          onChange={handleChangeInput1}
          value={OTPInput[0]}
        />
        <input
          placeholder=""
          type="tel"
          maxLength="1"
          name="otpValue2"
          ref={input2Ref}
          onChange={handleChangeInput2}
          value={OTPInput[1]}
        />
        {/* 扩展剩余两个输入框示例 */}
        <input
          placeholder=""
          type="tel"
          maxLength="1"
          name="otpValue3"
          value={OTPInput[2]}
        />
        <input
          placeholder=""
          type="tel"
          maxLength="1"
          name="otpValue4"
          value={OTPInput[3]}
        />
      </div>
    </>
  );
};

export default OTPVerification;

关键修复点

  • 包裹在函数组件内部:所有hooks和业务变量必须放在函数组件的作用域内,确保组件内部可访问。
  • 绑定第二个输入框的ref:之前的代码未给第二个input添加ref={input2Ref},导致input2Ref.current为null,无法调用focus方法。
  • 改为受控组件:给input绑定value属性,保证输入框内容与state同步,避免输入异常。
  • 函数式更新state:使用prev => [...prev]的形式更新状态,避免闭包导致的状态更新延迟问题。
  • 添加可选链防护:input2Ref.current?.focus()避免ref未挂载时调用focus出现报错。

内容的提问来源于stack exchange,提问作者Adex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:53:16