- 知识点
- 匹配中文
- 绑定事件
- onCompositionStart
- 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>
)
}