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

15次阅读

共计 1531 个字符,预计需要花费 4 分钟才能阅读完成。

  • 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

正文完
 0