2021年1月23日星期六

Handling both clicks and keypresses in React number input not working

I have part of some React code below, where I have a number input, I'd like to prevent people being able to click below 0, which I've done with the min attribute. However I've seen that it's possible to still manually key in negative numbers. After some googling I've seen that people can handle this with a keyPress check and looking at the character codes but for some reason I can't quite get this to work.

Are both handlers clashing with each other? My goal is to allow click increments to work for positive numbers and prevent negative and decimal numbers being allowed in the input.

It's a controlled input, where value is coming from state.

const handleChange = (e) => {      console.log(e.target.value);      setCount(e.target.value);    };      const handleKeyPress = (e) => {      console.log(e.target.value);      console.log(e.charCode);      if (e.charCode >= 48 && e.charCode <= 57) {        setCount(e.target.value);      }    };      return (      <section>        <h3>Input test</h3>        <form onSubmit={handleSubmit}>          <label htmlFor="amount">paragraphs:</label>          <input            type="number"            name="amount"            id="amount"            min="0"            value={count}            onKeyPress={handleKeyPress}            onChange={handleChange}          />  
https://stackoverflow.com/questions/65863888/handling-both-clicks-and-keypresses-in-react-number-input-not-working January 24, 2021 at 04:10AM

没有评论:

发表评论