Básicamente, quiero restablecer mi cantidad a 1 si es igual a 0 o menos. Entiendo que también necesito más validación, pero este es el primer requisito. Esto sigue restableciéndose tan pronto como empiezo a escribir, lo cual es obvio
Producto.componente.js
import { useState, useEffect } from "react"; const Product = () => { const [qty, setQty] = useState(1); useEffect(() => { }, [qty]); const handleChange = (currentQty) => { if (currentQty > 0) { console.log("ok"); //Do Somethong } else { setQty(1); } }; return ( <input type="text" value={qty} onChange={(e) => handleChange(e.target.value)} /> ); }; export default Product;Dado que está utilizando una entrada controlada, debe tener mucho cuidado al establecer el valor de la entrada porque hacerlo puede obstaculizar al usuario que intenta escribir su valor (como ha descubierto).
En cambio, yo:
qty cuando la cadena sea válidaAquí hay un ejemplo:
const { useState, useEffect } = React; const Product = () => { // The actual quantity const [qty, setQty] = useState(1); // The quantity string the user is editing const [qtyString, setQtyString] = useState(String(qty)); const handleChange = (valueString) => { // Always update the string setQtyString(valueString); // Is it a valid positive number? valueString = valueString.trim(); const value = valueString ? +valueString : NaN; if (isNaN(value) || value <= 0) { // No, our quantity is 1 (even though the string may // not be) setQty(1); } else { // Yes, use it setQty(value); } }; // Just for demo purposes: console.log(`qty = ${qty}, qtyString = ${JSON.stringify(qtyString)}`); return ( <input placeholder="Please provide a number > 0" pattern="^[1-9]\d*$" type="text" value={qtyString} onChange={(e) => handleChange(e.target.value)} /> ); }; const Example = () => { return <Product />; }; ReactDOM.render(<Example />, document.getElementById("root")); input[type=text]:invalid, input[type=text]:invalid::placeholder{ color: #800; } input[type=text]::placeholder { opacity: 0.8; font-size: .8em; } <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>El patrón de validación que he incluido ahí es para números enteros mayores que cero, querrás ajustarlo si quieres números parciales. (Pensé que "cantidad" probablemente era un número entero).