微软输入法输入中文清空内容

一、前提条件:

  • 微软输入法 关键原因
  • 输入中文
  • 有对输入内容做控制,只允许输入中文和数字和英文

二、问题现象:

image

三、解决方案:

对中文的处理放在compositionend事件里,其余数字和英文的处理在change事件

3.1解决之后的现象:

image

3.2 代码

React版解决示例

/*
 * Demo
 */
const Demo = ({
  reason = {} as ICauseItem,
  toggle,
  className = '',
  icon = false,
  level = 1,
  isAdv = false,
}: IProps) => {
  const [text, setText] = useState("");
  const write = useRef(false);
  const preText = useRef('');


  const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value || '';
    if (!write.current && (/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value) || !value)) {
      setText(value);
    } else if (write.current) {
      setText(value);
    }
  };

  const handleCompositionStart = () => {
    write.current = true;
    preText.current = text;
  };

  const handleCompositionEnd = () => {
    write.current = false;
    if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(text)) {
      setText(preText.current);
    }
  };

  return (
        <TextArea
          hasLimitHint
          maxLength={50}
          className={styles.textArea}
          placeholder="吐槽几句"
          value={text}
          onBlur={() => toggle(reason, level, true, text)}
          onChange={handleInput}
          // eslint-disable-next-line no-return-assign
          onCompositionStart={handleCompositionStart}
          // eslint-disable-next-line no-return-assign
          onCompositionEnd={handleCompositionEnd}
        />
  );
};

export default Reason;
posted @ 2022-12-14 10:53  胡姐姐  阅读(118)  评论(0编辑  收藏  举报