reactjs 根据react中的更改更新多个输入字段

ovfsdjhp  于 2022-12-18  发布在  React
关注(0)|答案(2)|浏览(234)

我真的希望你们能帮我这个忙。基本上,我正在创建一个发票表单,用户可以添加多个项目。我有4个字段为这些项目:项目名称、项目价格(单价)、项目数量、项目成本(该项目的总成本取决于数量)。我目前唯一的问题是,每次我添加一个新项目,前一个项目的ItemCost显示。我认为这是来自我的onchange事件,但我迷路了,不知道如何修复它。此外,请注意,虽然前三个项目是输入,最后一个是ItemCost,它实际上是一个p标签,因为它保存了总成本的值,而总成本是基于项目单价和数量自动计算的,所以不应编辑。
下面是我代码:

const [ItemName, setItemName] = useState("")
const [ItemPrice, setItemPrice] = useState("")
const [ItemQuantity, setItemQuantity] = useState("")
const [ItemCost, setItemCost] = useState("")
/* END OF DECLARING FORM FIELDS VALUES */

/* HANDLING DYNAMIC ITEMS FIELD */
const [inputFields, setInputFields] = useState([
    { item_name: '', item_price: '', item_quantity: '', item_cost: '', },
]);

const handleSubmit = (e) => {
    e.preventDefault();
    console.log("InputFields", inputFields);
};

const handleAdd = () => {
    setInputFields([...inputFields, { item_name: '', item_price: '', item_quantity: '', item_cost: '', }])
}

const handleRemove = (index) => {
    const values = [...inputFields];
    values.splice(index, 1);
    setInputFields(values);
}

我的输入字段

{inputFields.map((inputField, index) => (
                        <div key={index} className="item_container">
                            <div className='item_fields'>
                                <input
                                    name="item_name"
                                    value={inputField.ItemName}
                                    onChange={(e) => setItemName(e.target.value)}
                                    type="text"
                                    placeholder="Item Name"
                                />

                                <input
                                    name="item_price"
                                    value={inputField.ItemPrice}
                                    onChange={(e) => setItemPrice(e.target.value)}
                                    type="number"
                                    placeholder="Item Price"
                                />

                                <input
                                    name="item_quantity"
                                    value={inputField.ItemQuantity}
                                    onChange={(e) => setItemQuantity(e.target.value)}
                                    type="number" id=""
                                    placeholder="Quantity"
                                />

                                <p
                                    name="item_cost"
                                    value={inputField.ItemCost}
                                    onChange={(e) => setItemCost(e.target.value)}>
                                    {ItemCost}
                                </p>
                            </div>
                            <div className="buttons">
                                <button disabled={inputFields.length === 1} onClick={() => handleRemove(index)} className='remove_btn' >Remove</button>
                                <button onClick={() => handleAdd()}>Add an item</button>
                            </div>
                        </div>
                    ))}

the item fieldsthe code

oyxsuwqo

oyxsuwqo1#

我认为你写错了代码,当你更新一个项目的任何字段时,你需要更新项目数组中的正确对象,使用索引是最简单的方法

import { useState } from "react";

export default function ItemList() {
  const [inputFields, setInputFields] = useState([
    { 
      item_name: '', 
      item_price: '', 
      item_quantity: '', 
      item_cost: '', 
    },
  ]);

const handleSubmit = (e) => {
    e.preventDefault();
    console.log("InputFields", inputFields);
};

const handleAdd = () => {
    const newInputFields = [...inputFields];
    newInputFields.push({ 
      item_name: '', 
      item_price: '', 
      item_quantity: '', 
      item_cost: '', 
    });
    setInputFields(newInputFields);
}

const handleRemove = (index) => {
    const newInputFields = [...inputFields];
    newInputFields.splice(index, 1);
    setInputFields(newInputFields);
}

const onItemNameChange = (value, index) => {
  const newInputFields = [...inputFields];
  newInputFields[index].item_name = value;
  setInputFields(newInputFields);
}
const onItemPriceChange = (value, index) => {
  const newInputFields = [...inputFields];
  newInputFields[index].item_price = value;
  newInputFields[index].item_cost = 
    (parseInt(newInputFields[index].item_price, 10) || 0) * 
    (parseInt(newInputFields[index].item_quantity, 10) || 0);
  setInputFields(newInputFields);
}
const onItemQuantityChange = (value, index) => {
  const newInputFields = [...inputFields];
  newInputFields[index].item_quantity = value;
  newInputFields[index].item_cost = 
    parseInt(newInputFields[index].item_price, 10) * 
    parseInt(newInputFields[index].item_quantity, 10);
  setInputFields(newInputFields);
}

  return (
  <>
    {inputFields.map((inputField, index) => (
      <div key={index}>
          <div>
              <input
                  name="item_name"
                  value={inputField.ItemName}
                  onChange={(e) => onItemNameChange(e.target.value, index)}
                  type="text"
                  placeholder="Item Name"
              />

              <input
                  name="item_price"
                  value={inputField.ItemPrice}
                  onChange={(e) => onItemPriceChange(e.target.value, index)}
                  type="number"
                  placeholder="Item Price"
              />

              <input
                  name="item_quantity"
                  value={inputField.ItemQuantity}
                  onChange={(e) => onItemQuantityChange(e.target.value, index)}
                  type="number" id=""
                  placeholder="Quantity"
              />

              <p name="item_cost">
                  total: {inputField.item_cost || 0}
              </p>
          </div>
          <div className="buttons">
              <button 
                  disabled={inputFields.length === 1} 
                  onClick={() => handleRemove(index)} 
                  className='remove_btn' 
              >
                Remove
              </button>
              <button onClick={() => handleAdd()}>
                Add an item
              </button>
          </div>
      </div>
    ))}
  </>
  )
}
8wigbo56

8wigbo562#

试用这个解决方案。我会给予这个问题的视频教程在一个星期内在youtube上。你可以从“借记码”youtube频道观看。https://www.youtube.com/channel/UC-3yWzJVkRD8Jr5gzpupmog?sub_confirmation=1所以,订阅频道,喜欢/评论的视频,并学习这么多的东西。

import { useState } from "react";

function Form() {

    // State
    const [inputFields, setInputFields] = useState([{
        item_name: '',
        item_price: 0,
        item_quantity: 0,
        item_cost: 0,
    }]);

    const setItemName = (value, index) => {
        // const tempList = [...inputFields]
        inputFields[index].item_name = value;
        setInputFields([...inputFields])
    }
    const setItemPrice = (value, index) => {
        // const tempList = [...inputFields]
        inputFields[index].item_price = value;
        setCost(index, value, inputFields[index].item_quantity)
        setInputFields([...inputFields])
    }
    const setItemQuantity = (value, index) => {
        // const tempList = [...inputFields]
        inputFields[index].item_quantity = value;
        setCost(index, inputFields[index].item_price, value)
        setInputFields([...inputFields])
    }

    const setCost = (index, price, quantity) => {
        inputFields[index].item_cost = price * quantity;
        setInputFields([...inputFields])
    }

    const handleRemove = (e, index) => {
        inputFields.splice(index, 1);
        setInputFields([...inputFields]);
    }

    const handleAdd = (e) => {
        var list = [...inputFields];
        list.push({
            item_name: '',
            item_price: '',
            item_quantity: '',
            item_cost: '',
        })
        setInputFields(list)
    }

    return (
        <>
            {inputFields.map((field, index) => (
                <div key={index} className="item_container">
                    <div className='item_fields'>
                        <input
                            name="item_name"
                            value={field.item_name}
                            onChange={(e) => setItemName(e.target.value, index)}
                            type="text"
                            placeholder="Item Name"
                        />

                        <input
                            name="item_price"
                            value={field.item_price}
                            onChange={(e) => setItemPrice(e.target.value, index)}
                            type="number"
                            placeholder="Item Price"
                        />

                        <input
                            name="item_quantity"
                            value={field.item_quantity}
                            onChange={(e) => setItemQuantity(e.target.value, index)}
                            type="number" id=""
                            placeholder="Quantity"
                        />

                        <p name="item_cost">
                            {field.item_cost}
                        </p>
                    </div>
                    <div className="buttons">
                        <button disabled={inputFields.length === 1} onClick={(e) => handleRemove(e, index)} className='remove_btn' >Remove</button>
                        <button onClick={() => handleAdd()}>Add an item</button>
                    </div>
                </div>
            ))}
        </>
    );
}

export default Form;

相关问题