随笔 react 组件- 实现验证码输入框

252 阅读1分钟

背景

记录-简单实现一个手机验证码输入框

输入后,光标自动转到下一个输入框内,直到最后输入框内。

HTML

inputList为输入框的个数,为数组格式。

return (
  <div className={}>
    {
      inputList.map((item,index) => {
        return (
          <input
            ref={ref => {
              if (ref) {
                childRefs.current[index] = ref
              }
            }}
            className={}
            type=''
            maxLength={1}
            onChange={e => {
              inputchange(index, e.target.value)
            }}
          />
        )
      })
    }

  </div>
)

ts

  • 通过存储每一个 input 的ref 进行光标的聚焦。
  • onChange为验证码输入完成后,对外抛出的值,string类型
const inputchange = (index: number, value: string | number) => {
    if (value) {
      valueNums.push(value)
      const newindex = index + 1
      if (newindex < childRefs.current?.length) {
        childRefs.current[newindex].focus()
        return
      }
      onChange(valueNums.join(''))
    } else {
      const newindex = index - 1
      valueNums.pop()
      if (newindex >= 0) {
        childRefs.current[newindex].focus()
        return
      }
    }
  }