在React中,如何检查是否至少选中了一个复选框

时间:2019-03-27 18:02:32

标签: javascript reactjs checkbox

我用React编写了一个DOM组件,该组件被重新使用以生成复选框列表。我知道React元素在状态方面与React不同。但是,如何检查用户在React提交的表单上是否至少选择了1个复选框?

我已经在SO和Google中进行搜索,但是所有示例都在jQuery或Vanilla JS中。就我而言,我想要一个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>
    );
  }
}
infs = np.where(np.isinf(new_player_data))
infs

out: (array([ 261, 1162, 1190, 1339, 1365, 1451, 1656, 1736, 1878, 1954, 2189,
    2299, 2741, 3137, 3162, 3799, 3821, 3881, 4305]),
 array([ 3, 43, 43,  3, 43, 43, 43, 43, 43, 43, 23, 43,  3, 43, 43, 43,  3,
    23, 43]))

用户提交表单时,应检查是否至少选中了一个复选框,如果未选中,则阻止表单提交,即返回false!

2 个答案:

答案 0 :(得分:0)

您还应该将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},
  ...
]

答案 1 :(得分:-1)

下面显示了如何更改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);
    }
}