猿问

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

我使用编写了一个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!


MYYA
浏览 347回答 2
2回答

泛舟湖上清波郎朗

您还应该保持该checked属性的surveyResponse.newAnswers状态。然后,您将可以检查其中是否有一个true。例如:const nA = this.state.surveyResponse.newAnswersconst isChecked = nA.some(c => c.checked == true)if(isChecked) {&nbsp; //...if any of them has checked state}假设示例newAnswers数据:[&nbsp; {answer:'foo', checked: false},&nbsp; {answer:'bar', checked: true},&nbsp; ...]

互换的青春

下面显示了如何更改handleSubmit以读取表单数据:handleSubmit(event) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; const form = event.target;&nbsp; &nbsp; const data = new FormData(form);&nbsp; &nbsp; for (let name of data.keys()) {&nbsp; &nbsp; &nbsp; const input = form.elements[name];&nbsp; &nbsp; &nbsp; console.log(input);&nbsp; &nbsp; &nbsp; console.log('value:', input.value);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答