[英]How to get inputs data from multiple text box in for loop in React js and pass it to Api
I am trying to build a quiz application where I want to generate no of Question input fields based on admin inputs.我正在尝试构建一个测验应用程序,我想在其中不生成基于管理员输入的问题输入字段。
So suppose the admin enters 10 questions for the quiz.因此,假设管理员为测验输入了 10 个问题。
Then I am rendering the form inside for loop for 10 Questions and their answers respectively.然后我在 for 循环中分别呈现 10 个问题及其答案的表单。
The problem I am facing is I am not able to get all values from input fields.我面临的问题是我无法从输入字段中获取所有值。
Below is my demo code:下面是我的演示代码:
import { useState } from "react";
const MyComponent = () => {
const [inputs, setInputs] = useState({});
const handleChange = (e) =>
setInputs((prevState) => ({
...prevState,
[e.target.name]: e.target.value
}));
const finalData = (e) => {
e.preventDefault();
console.log("data", inputs);
};
function buildRows() {
const arr = [];
for (let i = 1; i <= 3; i++) {
arr.push(
<div key={i} id={i}>
<input name="Question" onChange={handleChange} />
<input name="option1" onChange={handleChange} />
<input name="option2" onChange={handleChange} />
<input name="option3" onChange={handleChange} />
<input name="option4" onChange={handleChange} />
</div>
);
}
return arr;
}
return (
<>
{buildRows()}
<button
onClick={(e) => finalData(e)}
variant="contained"
className="button-left"
sx={{ marginRight: 3.5 }}
>
Submit Quiz Questions
</button>
</>
);
};
export default MyComponent;
You could use the id
(or any other unique property, a unique name would probably be preferred) you're giving your div and build your object with that as an array index like so:你可以使用你给你的 div 的
id
(或任何其他独特的属性,一个独特的名字可能是首选)并用它构建你的 object 作为数组索引,如下所示:
const handleChange = (e) => {
const parent = e.currentTarget.parentNode;
const id = parent.id;
setInputs((prevState) => ({
...prevState,
[id]: {
...prevState[id],
[e.target.name]: e.target.value
}
}));
};
This produces an object like this:这会产生如下所示的 object:
{
"1":{
"Question":"1",
"option1":"2",
"option2":"3",
"option3":"4",
"option4":"5"
},
"2":{
"Question":"6",
"option1":"7",
"option2":"8",
"option3":"9",
"option4":"11"
},
"3":{
"Question":"22",
"option1":"33",
"option2":"44",
"option3":"55",
"option4":"66"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.