1. 问题描述
- 大部分人都是使用拼音输入;
antd的input组件在输入中文时会导致输入的拼音也会触发input的onChange事件;
- 会导致没必要的渲染和一些错误的触发
2. 核心思想
3. 解决方案
import { Input, InputProps } from 'antd';
import React, { ChangeEvent, useState, CompositionEvent, useEffect } from 'react';
interface ICommonInputProps extends Omit<InputProps, 'onChange'> {
onChange?: (value: string) => void;
}
const CommonInput = (props: ICommonInputProps) => {
const { value, onChange, ...restProps } = props;
const [curValue, setValue] = useState(value);
const [isComposing, setComposing] = useState(false);
const isChrome = navigator.userAgent.indexOf('WebKit') > -1;
useEffect(() => {
setValue(value);
}, [value]);
const handleCompositionStart = () => {
setComposing(true);
};
const handleCompositionEnd = (event: CompositionEvent<HTMLInputElement>) => {
setComposing(false);
if (isChrome) {
onChange?.(event.currentTarget.value);
}
};
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const rawValue = event.target.value;
setValue(rawValue);
if (!isComposing) {
onChange?.(rawValue);
}
};
return (
<Input
{...restProps}
value={curValue}
onChange={handleChange}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
/>
);
};
export default React.memo(CommonInput);