使用Keypress限制Input

const within = (keyCode) => {
  // Backspace 8, Tab 9,
  const specialKeys = [8, 9];
  return (
    (keyCode >= 48 && keyCode <= 57) ||
    (keyCode >= 65 && keyCode <= 90) ||
    (keyCode >= 97 && keyCode <= 122) ||
    specialKeys.some((k) => k === keyCode)
  );
};

const KIndex = ({ id, ...props }) => {
  useEffect(() => {
    const input = document.querySelector(`#${id}`);
    const keyPressFunction = (e) => {
      const keyCode = e.keyCode === 0 ? e.charCode : e.keyCode;
      if (!within(keyCode)) {
        e.preventDefault();
      }
    };
    input.addEventListener('keypress', keyPressFunction);
    return () => {
      input.removeEventListener('keypress', keyPressFunction);
    };
  }, [id]);

  return <Input id={id} {...props} />;
};
 
但这个做法,只能在英文输入法下使用,当遇到中文的符号就不行了。即使换Keyup、Keydown的做法也不合适。
 
建议做成在onChange中,拿到event.target,对value进行正则replace后,再set值,会比较合适。e.g. value.replace(/\W|[_]/g, '')
 
For Alphanumeric Input.
posted @ 2022-09-08 15:24  sssssssssssssrain  阅读(115)  评论(0)    收藏  举报