简体   繁体   中英

Why won't my text input allow me to change the value within it?

I defined the following input field in react:

const [products, setProducts] = useState(cart.products);

<div>
   {products.map((item) => (
    <input
       className="form-control-sm text-center mb-2"
       type="number"
       value={item.quantity}
       onChange={() => handleChange(event.target)}
       name="quantity"
    />
   ))}
</div>

I cannot change the value of item.quantity in the browser even though it is not specified as a read-only field.

Data:

cart 
 {_id: "5f15ee2c0b94bf240470d70d", user: "5f15ee2c0b94bf240470d70c", 
products: Array(3), __v: 0}
products: Array(3)
0:
product:
brand: "Apple"
category: []
color: "Silver"
images: ["latest-prduct-1.jpg"]
list_price: 220
name: "lorem ippsum dolor"
price: 120
rating: "5"
size: "Medium"
_id: "5f1864667c213e0f5779ee40"
__proto__: Object
quantity: 8
_id: "5f1f04267e422c266c5c1d42"

item.quantity refers to a fixed value within your object. Means you provide your input with a fixed value instead of a changeable state. Here is the react way of creating a controlled input field https://reactjs.org/docs/forms.html

In hooks that would be something like

const YourComp = ({initialQuantity}) => {
  const [quantity, setQuantity] = useState(initialQuantity)
  return (
    <div>
        <input
           className="form-control-sm text-center mb-2"
           type="number"
           value={quantity}
           onChange={ e => setQuantity(e.target.value)}
           name="quantity"
        />
    </div>
  )

}

And you map it as

{cart.products.map((item) => (
    <YourComp initialQuantity={item.amount} />
))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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