我创建了一个 OTP 屏幕,首先我创建状态挂钩,然后将该状态作为 useref 但是当我这样做时 console.log(otpState) 输出我首先打开屏幕和输入值后它保持空白
{"pin1": {"current": ""}, "pin2": {"current": ""}, "pin3": {"current": ""}, "pin4": {"current": ""}, "pin5": {"current": ""}, "pin6": {"current": ""}}
代码如下:
const [otpState, setOtpState] = useState({
pin1: '',
pin2: '',
pin3: '',
pin4: '',
pin5: '',
pin6: '',
})
otpState.pin1 = useRef(null);
otpState.pin2 = useRef(null);
otpState.pin3 = useRef(null);
otpState.pin4 = useRef(null);
otpState.pin5 = useRef(null);
otpState.pin6 = useRef(null);
otpState.pin1.current = '';
otpState.pin2.current = '';
otpState.pin3.current = '';
otpState.pin4.current = '';
otpState.pin5.current = '';
otpState.pin6.current = '';
console.log(otpState)
useEffect(() => {
otpState.pin1.current.focus();
}, [])
console.log(otpState)
有 6 个这样的 TextInput:
<TextInput
ref={otpState.pin1}
onChangeText={pin1 => {
setOtpState({ pin1: pin1 })
if (otpState.pin1 != "") {
otpState.pin2.current.focus();
}
}
}
defaultValue={otpState.pin1.current}
maxLength={1}
style={styles.OTPinput}
/>