【问题标题】:React JS Dynamic Form onChangeReact JS 动态表单 onChange
【发布时间】:2022-01-12 08:56:20
【问题描述】:

我有一个动态创建的字段(输入标签)

const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data

{navtive?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />
...
{rolls?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />

预期输出:

const output = {
    native: [{id: 1, fee: "12"}, {id: 5, fee: "2"}],
    rolls: [{id: 4, fee: "1332"}],
};

onChange函数:

const handleChange = (field, value, index) => {
    setData((prevState) => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    });
};

如何获得预期的输出?我在 onChange 函数中做错了什么。

谢谢

【问题讨论】:

    标签: javascript reactjs formik


    【解决方案1】:

    您好,我转载了一个示例,并添加了一些注释行

    codeSandBox :https://codesandbox.io/s/floral-bash-lrvkc?file=/src/App.js

    import React, { useState } from "react";
    import "./styles.css";
    
    function App() {
      const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);
    
      // handle input change
      const handleInputChange = (e, index) => {
        const { name, value } = e.target;
        const list = [...inputList];
        list[index][name] = value;
        setInputList(list);
      };
    
      // handle click event of the Remove button
      const handleRemoveClick = (index) => {
        const list = [...inputList];
        list.splice(index, 1);
        setInputList(list);
      };
    
      // handle click event of the Add button
      const handleAddClick = () => {
        setInputList([...inputList, { firstName: "", lastName: "" }]);
      };
    
      // CHANGE HERE: a flag to be set when there is an error
    
      const Submit = (e) => {
        e.preventDefault();
        console.log(inputList);
      };
    
      return (
        <div className="App">
          {inputList.map((x, i) => {
            return (
              <div className="box">
                <div>
                  <input
                    name="firstName"
                    placeholder="Enter First Name"
                    value={x.firstName}
                    onChange={(e) => handleInputChange(e, i)}
                  />
                </div>
                <div>
                  <input
                    className="ml10"
                    name="lastName"
                    placeholder="Enter Last Name"
                    value={x.lastName}
                    onChange={(e) => handleInputChange(e, i)}
                  />
                </div>
                <div className="btn-box">
                  {inputList.length !== 1 && (
                    <button className="mr10" onClick={() => handleRemoveClick(i)}>
                      Remove
                    </button>
                  )}
                  {inputList.length - 1 === i && (
                    <button onClick={handleAddClick}>Add</button>
                  )}
                </div>
              </div>
            );
          })}
          <button onClick={Submit}>Submit</button>
        </div>
      );
    }
    
    export default App;
    

    【讨论】:

    • 不错的代码 sn-p,也可以用文字简要说明解决方案。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2017-10-18
    • 2017-02-01
    • 2021-11-03
    • 2022-01-01
    相关资源
    最近更新 更多