该表单具有无线电按钮,该按钮从answers:[{}]
产生问题,它基于onChage
保存到answers:[{}]
。
演示:https://codesandbox.io/s/mm4qrv4o6j
问题和答案的当前状态
const question = {
questions: {
questionID: 1,
title: "Your gender ?",
values: [{ id: "1", value: "Male" }, { id: "2", value: "Female" }]
}
};
this.state = {
answers: [
{
questionID: "1",
answerValues: "2"
}
]
};
不幸的是无法更新答案,因为无线电不允许更改
<div className="form-group">
<label htmlFor={name}>{label}</label>
{options.map(option => {
return (
<div className="form-check" key={option.id}>
<label className="radio-inline" htmlFor={`${name}-${option.id}`}>
<input
name={name}
id={`${name}-${option.id}`}
data-question-id={questionID}
type="radio"
onChange={onChange}
value={option.id}
checked={option.id == checked.questionID}
/>{" "}
{option.value}
</label>
</div>
);
})}
</div>
要注意的一件事似乎不适合添加更多问题/答案(数组可能更合适(:
answered: {
answers: {
questionID: "1",
answerValues: "1"
}
}
第一个也是主要问题是,您的根组件在sub重新渲染时会控制自己的根组件,从不重新渲染。要解决此问题,您可以使用本地状态更新答案:
const question = {
questions: {
questionID: 1,
title: "Your gender ?",
values: [{ id: "1", value: "Male" }, { id: "2", value: "Female" }]
}
};
class App extends React.Component {
state = {
answered: {
answers: {
questionID: "1",
answerValues: "1"
}
},
}
updateAnswer = (newAnswer) => {
this.setState({
answered: {
answers: newAnswer,
},
});
}
render () {
return(
<div style={styles}>
<h2>Start editing to see some magic happen {"u2728"}</h2>
<hr />
<FormQuestion question={question.questions} answered={this.state.answered.answers} updateAnswer={this.updateAnswer}/>
</div>
)
}
};
最后一个问题是,检查的ID在一个令人困惑的命名为" Answervalues"中,而不是" QuestionId",因此更改为:
checked={option.id === checked.answerValues}
工作演示:https://codesandbox.io/s/62ovz1kql3
我建议您重构解决方案并将输入放入form
标签中。然后,只需从收音机中删除onChange
,然后将其添加到form
。然后再次运行您的代码。