小问题总结

146 阅读1分钟

1、使用正则的test配置时,会出现第一次为true,第二次为false的情况

原因:在g模式下,第二次的匹配是以第一次匹配的lastIndex为检索起点。

解决:

  • 不使用g模式

  • 每次使用test之后,对lastIndex手动重置为0

    let reg = /^[0-9._-]+[A-Za-z]*$/g const str = '1.2'

    reg.test(str)

    reg.lastIndex = 0

    reg.test(str)

2、想要在input中实现中文2个字符,英文1个字符的校验

import React, { useRef } from 'react';
import { Input } from 'antd';

// 支持中文算两个,英文算一个的input
export default function ECInput({ onChange = () => {}, type = '', ...other }) {
  const isCompositionRef = useRef(false);

  const onChangeValue = e => {
    if (!isCompositionRef.current) {
      onChange(e.target.value);
    }
  };
  const props = 、
    onChange: onChangeValue,
    onCompositionEnd(e) {
      onChange(e.target.value);
      isCompositionRef.current = false;
    },
    onCompositionStart() {
      isCompositionRef.current = true;
    },
    ...other
  };
  return type === 'textarea' ? <Input.TextArea {...props} /> : <Input {...props} />;
}

在第一次输入中文之后,不能再输入,第一次isCompositionRef为false,执行的事件为:onCompositionStart -> onCompositionEnd,输入成功。之后的输入的过程都是:onCompositionStart -> onChange -> onCompositionEnd,但是此时onChange中的if判断条件一直是false,所以一直不会执行,也就没有更改,也就导致不会执行onCompositionEnd,所以一直在执行onCompositionStart,输入的内容输入不进去。

3、@sentry/webpack-plugin一直下载不下来

使用curl -sL sentry.io/get-cli/ | bash,下载sentry-cli到全局,然后下载@sentry/webpack-plugin,就可以下载下来了。