动态

详情 返回 返回

在react中基於ant-design,封裝一箇中文輸入框,提高onchange性能 - 动态 详情

1 antd中,input組件在觸發onChange時,如果是中文輸入模式,會頻繁被觸發,導致頁面性能降低。尤其是在onChange時需要實時搜索的情況。
2 在mac設備下,如果在onChange中使用value.replace(/\s/g,''/), 會出現無法輸入中文的問題。優化之後,可以正常輸入。

默認情況下的Input組件:

image.png

優化之後的ChineseInput

image.png

調用方式: 和原始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

user avatar kaidiwen 头像
点赞 1 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.