简体   繁体   English

如何防止用户在 ReactJS 的输入表单字段中输入空格?

[英]How to prevent user from entering spaces in an input form field in ReactJS?

I have created a component called QueryForm to be used for search functionality.我创建了一个名为QueryForm的组件用于搜索功能。 I am returning in that component this:我在该组件中返回:

You can just use trim你可以只使用trim

export default function App() {
  const [val, setVal] = useState();

  return (
    <div className="App">
      <input
        value={val}
        onChange={(e) => {
          setVal(e.target.value.trim());
        }}
      />
    </div>
  );
}

Codesandbox 密码沙盒

You can replace the spaces to empty string while setting the value:您可以在设置值时将空格替换为空字符串:

const onChange = (event, { newValue }) => {
  setInputValue(newValue.replace(/\s/g, ''));
};

Good answers, but they are all assuming the input is controlled.很好的答案,但他们都假设输入是受控的。 For uncontrolled forms you want to make sure the validation is made before the onChange event is triggered.对于不受控制的 forms,您需要确保在触发 onChange 事件之前进行验证。 A solution that works for controlled and uncontrolled forms is this:适用于受控和不受控 forms 的解决方案是:

const onKeyDown = (event) => {
  if (event.code === 'Space') event.preventDefault()
}

Below with types included下面包括类型

const onKeyDown = (event: KeyboardEvent): void => {
  if (event.code === 'Space') event.preventDefault()
}

If there are more needs other than reject blank spaces the condition of that "if" statement could be a regex expression or a refactorized function.如果除了拒绝空格之外还有其他需求,那么“if”语句的条件可以是正则表达式或重构的 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM