在react中处理同一个表中的多个表单

问题描述 投票:0回答:1

建立一个可以包含多行的表格格式的表单输入,需要将多行输入的值作为对象存储在数组中(教育如代码所示)。

我很难根据教育索引将相应数据存储在教育数组中 如何解决这个问题?它是如何完成的?

const AddEducationDetails: React.FC = () => {
  const [showLevel, setShowLevel] = useState("upto 10");
  const [educations, setEducations] = useState<Education[]>([
    {
      level: "",
      studiedCourse: "",
      studiedAt: "",
      studiedFrom: "",
      passedYear: "",
      board: "",
      university: "",
      file: "",
    },
  ]);

  const handleInputChange = () => {};

  const handleLevelSelection = (
    e: React.ChangeEvent<HTMLSelectElement>,
    index: number,
  ) => {
    const { name, value } = e.target;
    setShowLevel(value);
    console.log(index);
  };
  return (

      <table className="min-w-full overflow-hidden rounded-lg bg-[#373747]">
        //thead
        <tbody>
          {educations.map((education, index) => (
            <tr key={index} className="border border-gray-600">
              <td className="px-4 py-2">
                <select
                  name="level"
                  onChange={(e) => handleLevelSelection(e, index)}
                  className="mb-4 w-[110px] flex-1 rounded-md border-0 bg-gray-700 p-2 text-gray-200 focus:bg-gray-600 focus:outline-none focus:ring-1 focus:ring-blue-500"
                >
                  <option value="upto 10">Upto 10</option>
                  <option value="+2">+2</option>
                  <option value="above +2">Above +2</option>
                </select>
              </td>
              <td className="px-4 py-2">
                <Input
                  type="text"
                  value={education.studiedCourse}
                  onChange={handleInputChange}
                />
              </td>
             //multiple td with form inputs 
 
            </tr>
          ))}
        </tbody>
      </table>
  );
};
reactjs typescript html-table
1个回答
0
投票
  1. 使用 Object.keys(education) 检索每个字段的键,以使用单个组件处理多个字段。
  2. 将密钥传递给每个字段的 name 属性,以标识哪个字段发生了更改。
  3. 在onChange事件中,同时传递(event,index)来确定字段及其所属教育对象的索引。
  4. 从事件中提取 event.target.name 和 event.target.value 以获取字段名称和新值。
  5. 使用扩展运算符 (...) 复制 educations 数组,然后创建一个新数组并更新指定索引处的对象。
  6. 使用索引更新复制数组中对象的特定字段。
  7. 最后,将更新后的数组传递给setEducations函数来更新状态。

需要修复什么

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.