react 原生 input 实现只能输入中文

236 阅读1分钟
  • 知识点
    1. 匹配中文
    2. 绑定事件
    3. onCompositionStart
    4. input赋值
  • 代码
import React, { useState, useRef } from 'react'

function LoginHome(props) {
  const inputRef = useRef()
  const [isOnComposition, setIsOnComposition] = useState()
  const handleComposition = evt => {
    if (evt.type === 'compositionend') {
      setIsOnComposition(false)
      return
    }
    setIsOnComposition(true)
  }
  const validateChinese = (val, fn, ...args) => {
    if (!isOnComposition) {
      // 非中文
      const reg = /[^\u4e00-\u9fa5]/g
      if (val.match(reg)) {
        alert('请输入中文')
        fn && fn.apply(fn, [...args, val.replace(reg, '')])
      }
    }
  }
  const setInputValue = (ref, val) => {
    if (!ref) {
      return
    }
    ref.value = val
  }
  const handleCompositionProps = {
    onCompositionStart: handleComposition,
    onCompositionUpdate: handleComposition,
    onCompositionEnd: handleComposition
  }
  return (
    <div>
      <input ref={ inputRef } onChange={ (e) => validateChinese(e.target.value, setInputValue, inputRef.current) } { ...handleCompositionProps }></input>
    </div>
  )
}