【发布时间】:2020-05-03 18:21:16
【问题描述】:
我是一名学生,我的项目之一是测验。我从后端获取问题,在 QuizContainer 中执行 componentDidMount,然后将每个问题作为道具传递给 QuizForm。在 QuizForm 中,每个问题都有 5 个单选按钮,代表从非常不同意到非常同意的范围。当我在子 (QuizForm) 组件中设置 setState 时,它只注册最后一个 onClick 事件,并且只将其发送给父级。我认为它可能会将每个问题都呈现为它自己的 QuizForm,但我不确定如何在父级内部收集所有这些数据(也许作为父级的状态,但我不确定我会怎么做那个)。
下面是代码供参考:
QuizContainer
state = {
all: []
}
handleSubmit = (evt, quizObj) => {
evt.preventDefault()
this.setState = {
all: [...this.state.all, quizObj]
}
}
render() {
return (
<container className="quiz">
<h5>For each of the following statements choose on a scale of 1 - 5, one strongly disagree and 5 being strongly agree, and 3 being neutral. </h5>
<div> {this.props.questions.questions.map(question => <QuizForm question={question} key={question.id} handleSubmit={this.handleSubmit}/>)}
<input form="quiz-form" type="submit" value="Submit" />
</div>
</container>
)
}
QuizForm
state = {
question: [],
answer: []
}
handleChange = (evt) => {
let name = evt.target.name
let value = evt.target.value
this.setState({
questions: [...this.state.questions, name],
answers: [...this.state.answers, value]
})
}
render() {
return (
<form id="quiz-form" onSubmit={(evt) => this.props.handleSubmit(evt, this.state)}>
<label htmlFor="question">{this.props.question.question}</label>
<input onChange={this.handleChange}
type="radio"
name={this.props.question.id}
value={0}
/>
<input onChange={this.handleChange}
type="radio"
name={this.props.question.id}
value={25}
/>
</form>
)
}
【问题讨论】:
-
在您的
QuizContainer中,您调用setState错误,而且您使用的是<container ../>,是拼写错误吗?
标签: reactjs forms components parent-child