如何解决如何使用反应将输入输入到结构化数组嵌套中,数组大小将动态决定
"questions":[
{"question": "Trial question","options":[{"A":"hi","B":"hi","C":"hi","D":"hi"}],"ans":"A","marks":5},{"question": "Trial question2","marks":1},"marks":2}
]
这里的数组大小是动态的,用户可以输入n个这个结构。(这里大小是3)
我正在尝试这种方式来获取输入
constructor() {
super();
this.state = {
name: "",subject: "",numQuestion: 0,totalNumQuestion: "",questions: [
{
question: "",options: [
{
A: "",B: "",C: "",D: "",},],marks: "",ans: "",};
this.handleSubmit = this.handleSubmit.bind(this);
}
这里我采用以下方式输入
for (let i = 1; i <= this.state.numQuestion; i++) {
inputs.push(
<input
placeholder="Question name"
name={`question`}
onChange={this.onChange}
required
/>,<br />,<input
placeholder="Option A"
name={`A`}
onChange={this.onChange}
required
/>,<input
placeholder="Option B"
name={`B`}
onChange={this.onChange}
required
/>,<input
placeholder="Option C"
name={`C`}
onChange={this.onChange}
required
/>,<input
placeholder="Option D"
name={`D`}
onChange={this.onChange}
required
/>,<input
placeholder="Answer"
name={`ans`}
onChange={this.onChange}
required
/>,<input
placeholder="Marks"
name={`marks`}
onChange={this.onChange}
required
/>,<br />
);
解决方法
您首先需要根据 numberofQuestions 初始化 template.HTML("your html here")
中的问题状态,我意识到当前状态中的问题数为零,不确定您是从用户输入中获取它还是从您的代码。
componentDidMount
对于选项输入和其他输入,您还需要不同的 componentDidMount(){
let quest = [];
for (let i = 0; i < this.state.numQuestion; i++) {
quest.push(null)
}
this.setState({questions: quest})
}
和 onChange
函数。
onChangeOption
然后你可以渲染元素
const onChange = (index,name,value) => {
// declare a temp questions array
const questions = this.state.questions
// get the current question being changed
const currentQuestion = questions[index];
// if question has not been changed/added
if (!currentQuestion) {
const newQuestionObject = {
question: "",options: [
{
A: "",B: "",C: "",D: "",},],marks: "",ans: "",}
newQuestionObject[name] = value;
questions[index] = newQuestionObject;
this.setState({ questions })
} else {
currentQuestion[name] = value;
questions[index] = currentQuestion;
this.setState({ questions })
}
}
onChangeOption = (index,value) => {
// declare a temp questions array
const questions = this.state.questions
// get the current question being changed
const currentQuestion = questions[index];
// if question has not been changed/added
if (!currentQuestion && currentQuestion.question) {
const newQuestionObject = {
question: "",}
newQuestionObject.options[0][name] = value;
questions[index] = newQuestionObject;
this.setState({ questions })
} else {
currentQuestion.options[0][name] = value;
questions[index] = currentQuestion;
this.setState({ questions })
}
}
,
当您的状态变得如此复杂时,最好使用 useReducer 钩子。 在这里,您可以创建一个商店(您的问题数组),然后编写不同的操作来对您的状态执行不同的操作。 这是 useReducer 的链接: https://reactjs.org/docs/hooks-reference.html#usereducer
您可以使用上面链接中的示例来满足您的需要。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。