基于antd-input & tsx封装一个按固定位数、固定符号分隔内容的输入框

发布时间 2023-08-04 14:21:37作者: 结网
/**
 * 可在每四位字符间插入一个空格的输入框
 */
import { Input } from 'antd';
import { useEffect } from 'react';
const InputGap = (props: any) => {
  const { useGap, value, onChange } = props;
  // 非onChange事件变更value
  useEffect(() => {
    value && gapChange({ target: { value: value } });
  }, [value]);

  // useGap 可启用字符串分隔
  const gapChange = (e: any) => {
    const { value: inputValue } = e?.target;
    let newstr: string = '';
    if (useGap) {
      let valList: string[] = inputValue?.replaceAll(' ', '')?.split('');
      valList?.forEach((item, index) => {
        newstr += index % 4 === 0 && index !== 0 ? ` ${item}` : item;
      });
    } else {
      newstr = inputValue;
    }
    onChange(newstr);
  };

  return (
    <>
      <Input {...props} onChange={gapChange} />
    </>
  );
};

export default InputGap;