[英]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.即使未将 item.quantity 指定为只读字段,我也无法在浏览器中更改它的值。
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. item.quantity 是指 object 中的固定值。 Means you provide your input with a fixed value instead of a changeable state.
意味着您为输入提供固定值,而不是可变的 state。 Here is the react way of creating a controlled input field https://reactjs.org/docs/forms.html
这是创建受控输入字段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而你 map 它为
{cart.products.map((item) => (
<YourComp initialQuantity={item.amount} />
))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.