React?Hooks?实现的中文输入组件(react绑定this)学会了吗

随心笔谈12个月前发布 admin
85 0

import { useRef, useState } from “react”;
export function ChineseInput(params){
const { onInput=()=> {} }=params;
const lockRef=useRef(false);
// preview 用于预览,不然都不知道自己打的什么内容
const [preview, setPreview]=useState(value);
// 进入组合输入状态
const handleStart=()=> {
lockRef.current=true
};
const handleInput=event=> {
// 不管状态如何,总是需要预览的
setPreview(event.target.value);
// 处于组合输入状态,不予处理
if(lockRef.current) return;
// 非组合输入状态,触发 onInput
onInput(event);
};
// 选字结束,触发 onInput
const handleEnd=event=> {
setPreview(event.target.value);
lockRef.current=false;
onInput(event);
};
return (
<input
{…params}
onCompositionEnd={handleEnd}
onCompositionStart={handleStart}
onInput={handleInput}
/>
)
}

© 版权声明

相关文章