使用.focus()时谷歌浏览器onChange函数调用两次的问题
场景如下 我有六个Input框 我想要实现类似支付宝填密码的那种效果
输入时自动聚焦在下一个Input框里
[...new Array(6)].map((item, i) =>
(
<Col span={4} key={i}>
<input
className='input'
ref={inputDom[i].ref}
maxLength={1}
onChange={(e) => onChange(e, i)}
/>
</Col>
)
)
尝试解决办法:改成onInput,但是还是有bug
[...new Array(6)].map((item, i) =>
(
<Col span={4} key={i}>
<input
className='input'
ref={inputDom[i].ref}
maxLength={1}
onInput={(e) => onChange(e, i)}
/>
</Col>
)
)
最终解决办法:在onChange事件中使用setTimeout包裹,怀疑是React17渲染的问题。。待深入研究
const onTypeCaptcha = (e, index) => {
submitNum < 3 && setValidateMsg()
let _verCodeList = JSON.parse(JSON.stringify(verCodeList))
_verCodeList[index] = e.target.value
setVerCodeList(_verCodeList)
setTimeout(() => {
e.target.value.length !== 0 &&
index < 5 &&
inputDom[index + 1].ref.current.focus()
e.target.value.length === 0 &&
index > 0 &&
inputDom[index - 1].ref.current.focus()
})
}