我使用编写了一个Checkbox组件,该组件React被重新使用以生成复选框列表。我知道React元素DOM在状态方面与a有所不同。但是,如何检查用户是否在表单提交中选择了至少1个复选框React?
我在SO和Google中进行了搜索,但所有示例都在jQuery或Vanilla JS中。就我而言,我想React举一个例子。
零件
const Checkbox = ({ title, options, id, name, onChange }) => {
return (
<div className="checkbox-group">
<h4>{title}</h4>
{options.map(option => (
<label htmlFor={`${name}-${index}`} key={`${name}-${index}`}>
<input
type="checkbox"
name={name}
value={option}
onChange={onChange}
id={`${name}-${index}`}
/>
<span> {option}</span>
</label>
))}
</div>
);
};
class Form extends Component {
...
handleChange(event) {
let newSelection = event.target.value;
let newSelectionArray;
newSelectionArray = [
...this.state.sureveyResponses.newAnswers,
newSelection,
];
this.setState(prevState => {
return {
surveyResponse: {
...this.state.surveyResponse,
newAnswers: newSelectionArray,
}
)
}
handleSubmit() {
// I'm guessing this doesn't work in React as it's using its own state!
let checkboxes = document.querySelectorAll('[name="quiz-0"]:checked');
for (let chk in checkboxes) {
if (chk.checked) {
return true;
}
}
alert('Please choose at least one answer.');
return false;
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h4>Choose</>
{this.state.surveyQuiz.map((quiz, index) => {
return (
<div key={index}>
<Checkbox
title={quiz.question}
options={quiz.answers}
name={`quiz-${index + 1}`}
onChange={this.handleChange}
/>
</div>
);
})};
<button>Save answer(s)</span>
</form>
);
}
}
用户提交表单时,应检查是否至少选中了一个复选框,如果未选中,则阻止表单提交,即返回false!
泛舟湖上清波郎朗
互换的青春
相关分类