首页 > 解决方案 > 单击签入反应时,将行数据存储为状态中的对象数组

问题描述

<table className="table sm-td table-bordered mt-2">
          <tbody>
            {step1response.skills.length? (
              step1response.skills.slice(0, 5).map((t) => (
                <tr key={t}>
                  <td>
                    <input type="checkbox" onChange={handleSkills}/>
                  </td>
                  <td>{t}</td>
                  <td>
                    <select name="skill_type" className="custom-input p1" onChange={handleChange}>
                      <option>Select</option>
                      <option value="Must Have" selected>Must have</option>
                      <option value="Nice to have">Nice to have</option>
                    </select>
                  </td>
                  <td>
                    <select name="level_type" className="custom-input p1" onChange={handleChange}>
                      <option>Select</option>
                      <option value="Distinguished level" selected>Distinguished Level</option>
                      <option value="Novice level">Novice Level</option>
                    </select>
                  </td>
                </tr>

所以我正在通过一个包含技能名称的数组进行映射......我希望用户在表格行的其他两个选择下拉列表中选择级别和技能类型。当用户单击该复选框并收集他选择的任何值时,我无法弄清楚如何存储选定的行数据,因此我的状态看起来像:

const [state,setState] = useState([{
name:"",
skill_type:"",
level_type:""
}])

标签: javascriptnode.jsreactjshtml-table

解决方案


您需要在下拉选择中为每个技能对象添加属性,如下所示:

handleChangeSkillType =(e)=>{
   skills[index].skill_type=e.target.value
}
handleChangeLevelType =(e)=>{
   skills[index].level_type=e.target.value
}
handleSkills=(e,index)=>{

   // you will be able to access slected row value here by skills[index]

}

并且在调用 onChange 时传递索引作为所有参数的参数,例如:

onChange={(e)=>handleChangeLevelType(e,index)}
onChange={(e)=>handleSkills(e,index)}
onChange={(e)=> handleChangeLevelType(e,index)}

并将索引传递给映射函数

step1response.skills.slice(0, 5).map((t,index) => 

推荐阅读