正文

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

文章摘要

这篇文章展示了如何使用 React 实现组合输入状态的处理逻辑。文章通过定义 `handleStart`、`handleInput` 和 `handleEnd` 三个事件函数,演示了如何在组合输入状态下实时预览输入内容,并在状态切换时正确触发 `onInput` 处理。文章重点介绍了 `useRef` 和 `useState` 的使用,以及如何通过事件监听实现状态管理。

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} /> ) }