简体   繁体   English

如何阻止事件在 React 中被进一步处理

[英]How to stop an event from being further processed in React

I have a text input in my React app which I don't want to take inputs which are greater than 100. For example, If the entered value is 105, an alert is created and the event is terminated ie changing input value is not gonna happen.我的 React 应用程序中有一个文本输入,我不想接受大于 100 的输入。例如,如果输入的值为 105,则会创建警报并终止事件,即不会更改输入值发生。 Now I couldn't find a way to do this inside onChange function.现在我找不到在onChange function 中执行此操作的方法。 Any help would be highly appreciated.任何帮助将不胜感激。

<input onChange={handleChange} name="t"/>

handleChange = e => {
  if(e.target.value > 100){
    alert("High")
    //Here I want to stop event so that changing text in the input doesn't happen
  }
} 

Make it a controlled input and only set the value if a condition is met.使其成为受控输入,并且仅在满足条件时才设置值。

 const App = () => { const [value, setValue] = React.useState(""); const handler = (e) => { const value = Number(e.target.value); value <= 100 && setValue(value); }; return ( <input onInput={handler} type="number" value={value} /> ); } ReactDOM.render(<App/>, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

handleChange = e => {
  if(e.target.value > 100){
    alert("High");
    e.target.value = "";
  }
  else {
    // your normal processing
  }
} 

should work.应该管用。

Explanation: Your code would simply not be executed in case the if condition is true.说明:如果 if 条件为真,您的代码将不会被执行。 The line e.target.value = "" doesn't actually "not show" the users input (as asked for in comment), but rather overrides it with empty string. e.target.value = ""行实际上并没有“不显示”用户输入(如评论中所要求的),而是用空字符串覆盖它。

Mention: This solution has nothing to do with React, but rather works in any context.提及:此解决方案与 React 无关,而是适用于任何上下文。

If I'm understanding you properly, if a specific condition is not met, you want to prevent the input from reflecting the text the user just entered.如果我正确理解您,如果不满足特定条件,您希望阻止输入反映用户刚刚输入的文本。

In order to accomplish this, you'll need to control your input's value via state.为了实现这一点,您需要通过 state 控制输入的值。

That means doing something like this:这意味着做这样的事情:

<input onChange={handleChange} name="t" value={this.state.tInput}/>

handleChange = e => {
  if(parseInt(e.target.value) > 100) {

    alert("High")
    // set input state here to previous value to re-render and remove unwanted input values from input
    return this.setState(({tInput}) => ({tInput}))
  }
  return this.setState({tInput: e.target.value})
} 

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

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