简体   繁体   English

React JS 将动态 object 值从 FORM 添加到对象

[英]React JS add dynamic object values from FORM to objects

I have array of objects where i need to an key value我有一组对象,我需要一个键值

State: State:

const [row, setRow] = useState([{ nameofthework: "", schedulerefNo: "", unitprice: "", qty: "", uom: "", gst: "", total: "" }]);

The form input change function表格输入变化function

const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...row];
    list[index][name] = value;
    setRow(list);
    console.log(row);  // Prints out the each row object into and array of objects
};

const handleQty = (e) => {
    const scheduleNumberForQuantity = e.target.value;
    projectScheduleNumber?.filter((v) => {
        if(v["Schedule No"] === scheduleNumberForQuantity ) {
            setScheduleQuantity(v["LOA Qty"]); // return only integer example 1000
        }
    })
}

My Form我的表格

<Form.Control as="select" name="schedulerefNo" value={x.schedulerefNo} onChange={e => {handleInputChange(e, i); handleQty(e)}}>

How to add handleQty value to row state?如何将handleQty值添加到行state?

Same way as in the handleInputChange?与handleInputChange中的方式相同吗?

const list = [...row];
const item = list[index];
if (item) {
  item.qty = e.target.value;
  setRow(list);
}

Also in React it is not good practice to mutate data.同样在 React 中,改变数据也不是一个好习惯。 You should rather create new list with the updated item.您应该使用更新的项目创建新列表。

Whats the best way to update an object in an array in ReactJS? 在 ReactJS 的数组中更新 object 的最佳方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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