Based on ant-design in react, encapsulate a Chinese input box to improve onchange performance

jsoncode
中文
1 In antd, when the input component triggers onChange, if it is in Chinese input mode, it will be triggered frequently, resulting in reduced page performance. Especially if you need to search in real time when onChange.
2 Under the mac device, if you use value.replace(/\s/g,''/) in onChange, there will be a problem that Chinese cannot be entered. After optimization, it can be input normally.

Input component by default:

image.png

ChineseInput after optimization

image.png

Calling method: The same as the original Input component, no additional api is used

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;
    }
  }
}

How to use:

 <ChineseInput
  autoClear={true}
  value={value}
  onChange={onChange}
  {...}
/>

Component source code: github.com/jsoncode/empty-react-antd-ts/tree/main/src/components/ChineseInput

阅读 829

前端黑科技
前端那些你不知道,又必须掌握的小技巧

I'm jsoncode

3.9k 声望
778 粉丝
0 条评论

I'm jsoncode

3.9k 声望
778 粉丝
文章目录
宣传栏