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
相关产品推荐
相关产品推荐

