猿问

如何在反应中获取表单提交的复选框数据

我正在使用复选框进行反应。


我正在使用从服务器获取的动态数据制作我的复选框,并相应地在 UI 上显示选中和未选中状态。


对于表单验证,我正在使用react-form-hook并在提交时获取数据,我正在handleSubmit使用react-form-hook


我唯一的问题是我无法按照我的要求获取数据。


我的数据:


    let dta = [

    {

      p_id: 2,

      p_name: "isco",

      isChecked: true

    },

    {

      p_id: 2,

      p_name: "david",

      isChecked: false

    }

  ];

我的表格:


<form onSubmit={handleSubmit(submitForm)}>

    {dta.map((li, index) => (

      <div key={index}>

        <input

          type="checkbox"

          id={li.component_name}

          name={`data.${li.p_name}`}

          ref={register}

          defaultChecked={li.isChecked}

        />

        <label htmlFor={li.p_name}>{li.p_name}</label>

      </div>

    ))}

    <button>Submit</button>

  </form>

在提交时,我得到这样的数据


{"data":[{"isco":false},{"david":true}]} 

但是我想要它的方式如下


    {

  "data": [

    {

      "p_name": "isco",

      "isChecked": true,

      "p_id":1

    },

    {

      "p_name": "david",

      "isChecked": false,

       "p_id":2

    }

  ]

}

编辑

代码沙箱


宝慕林4294392
浏览 111回答 1
1回答

开满天机

我正在更改代码export default function App() {&nbsp;&nbsp;&nbsp; let data = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; p_id: 1,&nbsp; &nbsp; &nbsp; p_name: "isco",&nbsp; &nbsp; &nbsp; isChecked: true&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; p_id: 2,&nbsp; &nbsp; &nbsp; p_name: "david",&nbsp; &nbsp; &nbsp; isChecked: false&nbsp; &nbsp; }&nbsp; ];&nbsp; const [dataForm, setDataForm] = useState(data);&nbsp; const changeCheck = (id) => {&nbsp; &nbsp; console.log(id);&nbsp; &nbsp; let temp = [...dataForm];&nbsp; &nbsp; const index = temp.findIndex((x) => x.p_id === id);&nbsp; &nbsp; if (index === -1) return;&nbsp; &nbsp; temp[index].isChecked = !temp[index].isChecked;&nbsp; &nbsp; setDataForm(temp);&nbsp; };&nbsp; const handleSubmit = () => {&nbsp; &nbsp; console.log(`{"data":` + JSON.stringify(dataForm) + `}`);&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; &nbsp; {dataForm.map((li, index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div key={index}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="checkbox"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; checked={li.isChecked}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; changeCheck(li.p_id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label htmlFor={li.p_name}>{li.p_name}</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" onClick={handleSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Submit&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; </div>&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答