关于antd:在react中基于antdesign封装一个中文输入框提高onchange性能

  • 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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理