我使用编写了一个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!
2 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
您还应该保持该checked属性的surveyResponse.newAnswers状态。然后,您将可以检查其中是否有一个true。例如:
const nA = this.state.surveyResponse.newAnswers
const isChecked = nA.some(c => c.checked == true)
if(isChecked) {
//...if any of them has checked state
}
假设示例newAnswers数据:
[
{answer:'foo', checked: false},
{answer:'bar', checked: true},
...
]
互换的青春
TA贡献1797条经验 获得超6个赞
下面显示了如何更改handleSubmit以读取表单数据:
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
for (let name of data.keys()) {
const input = form.elements[name];
console.log(input);
console.log('value:', input.value);
}
}
添加回答
举报
0/150
提交
取消