【问题标题】:How to increase or decrease the values ​of multiple inputs of array?如何增加或减少数组的多个输入的值?
【发布时间】:2021-02-16 02:11:25
【问题描述】:

就是这样:

const [count, setCount] = useState(1 as any)

{items.map((item: any) => (...

然后将数组中的项目映射到购物车中。我希望能够增加或减少数量。

<input
 type="number"
 min="1"
 value={count}
 onChange={(event): any => {
 setCount(event.target.value)
 }}
/>

它改变了所有项目的价值。但我想独立改变元素的值。

【问题讨论】:

    标签: javascript typescript input increment decrement


    【解决方案1】:

    试试这个方法

    const [items, setItems] = useState(items); // items array []
    
    const onTextChanged = (index, value) => {
        const items = [...items]; 
        items[index].count = value; <-- "count" is example key for showing way out of this -->
        setItems(items);
    }
    
    {items.map((item, index) => (
    
     <input
      type="number"
      min="1"
      value={item.count || 0}
      onChange={(event): any => {
        onTextChanged(index, event.target.value)
      }}
     />
    
    )}
    

    【讨论】:

    • 看起来不错,但我没有数据值。 setItems(data)
    • setItems 是一种使用 Hooks 使用新数据集重置状态的方法。这样所有计数都单独维护
    • “数据”未定义
    • 现在输入字段显示值但不响应向上和向下箭头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多