- 1 antd中,input组件在触发onChange时,如果是中文输出模式,会频繁被触发,导致页面性能升高。尤其是在onChange时须要实时搜寻的状况。
- 2 在mac设施下,如果在onChange中应用value.replace(/\s/g,''/), 会呈现无奈输出中文的问题。优化之后,能够失常输出。
默认状况下的Input组件:
优化之后的ChineseInput
应用形式: 和原始Input组件应用形式一样,没用额定api
index.tsx
import React, { FC, useEffect, useRef, useState } from 'react';import { Input, InputProps } from 'antd';import styles from './index.module.less'interface IProps extends InputProps { [propName: string]: any; value?: string;}const Index: FC<IProps> = ( { value = '', onChange, onInput, onCompositionStart, onCompositionEnd, ...resetProps }) => { const chineseInputting = useRef(false); // 是否是中文(爽字节字符的输出)模式 const [val, setVal] = useState('') useEffect(() => { setVal(value) }, [value]) // 优化搜寻 const change = (e: any) => { onChange && onChange(e) } return ( <Input className={styles.chineseInput} {...resetProps} value={val} onChange={(e: any) => { if (e.target.value === '') { change(e) } setVal(e.target.value) }} onInput={(e: any) => { onInput && onInput(e) if (!chineseInputting.current) { change(e) } }} onCompositionStart={(e: any) => { onCompositionStart && onCompositionStart(e) chineseInputting.current = true; }} onCompositionEnd={(e: any) => { onCompositionEnd && onCompositionEnd(e) if (chineseInputting.current) { change(e) chineseInputting.current = false; } }} /> );};export default Index;
index.module.less
.chineseInput { :global { // 暗藏safari表单输出项右侧呈现的图标 input::-webkit-contacts-auto-fill-button { visibility: hidden; display: none !important; pointer-events: none; position: absolute; right: 0; } }}
应用形式:
<ChineseInput autoClear={true} value={value} onChange={onChange} {...}/>
组件源码: github.com/jsoncode/empty-react-antd-ts/tree/main/src/components/ChineseInput