如何防止用户在react中输入负数?

the*_*rer 5 javascript frontend web ecmascript-6 reactjs

我想限制用户输入负值。我正在使用分钟=“0”。这样我可以限制用户递减到0,即用户只能将值递减到0。但是他们可以输入“-”。在react js中如何防止。

https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />
Run Code Online (Sandbox Code Playgroud)

小智 10

您可以onKeyPress向输入元素添加一个侦听器,该侦听器将在 之前触发onChange并调用一个函数,该函数将在按下减号按钮时阻止默认行为。

const preventMinus = (e) => {
    if (e.code === 'Minus') {
        e.preventDefault();
    }
};

<input               
  type="number"
  min="0"
  onKeyPress={preventMinus}
/>
Run Code Online (Sandbox Code Playgroud)

请注意,这仍然允许将负值粘贴到输入中。为此,您可以添加一个onPaste侦听器并检查剪贴板数据以查看其是否为负并防止默认行为。

const preventPasteNegative = (e) => {
    const clipboardData = e.clipboardData || window.clipboardData;
    const pastedData = parseFloat(clipboardData.getData('text'));

    if (pastedData < 0) {
        e.preventDefault();
    }
};

<input               
  type="number"
  min="0"
  onPaste={preventPasteNegative}
  onKeyPress={preventMinus}
/>
Run Code Online (Sandbox Code Playgroud)


Moh*_*him 3

处理空输入和负数

// Converting App into Class-Component
class App extends React.Component {
  // Set State
  constructor(props) {
    super(props);
    this.state = {
      number: ""
    };
  }

  render() {
    return (
      <div className="App">
        <input
          type="number"
          min="0"
          step="1"
          onChange={(e) => {
            let val = parseInt(e.target.value, 10);
            if (isNaN(val)) {
              this.setState({ number: "" });
            } else {
              // is A Number
              val = val >= 0 ? val : 0;
              this.setState({ number: val });
            }
          }}
          className="w-100"
          // Assign State
          value={this.state.number}
        />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)