我如何要求至少选中一个复选框,以便用户提交表单?

时间:2019-01-18 20:57:15

标签: javascript reactjs

我有一个checkboxgroup component,我想对其进行一些输入验证。用户提交表单之前,至少需要选中一个复选框。

        <legend>Choose field names</legend>
        <CheckboxGroup
          checkboxDepth={5}
          name="fieldNames"
          value={this.state.fieldNames}
          onChange={this.fieldNamesChanged}
          required
        >
          {fields &&
            fields.map(field => {
              return (
                <li>
                  <Checkbox value={field.name} />
                  {field.name}
                </li>
              );
            })}

使用I currently have in my codesandbox格式,无需选中任何复选框即可提交表单。可以使用required属性来解决此问题,还是需要跟踪此组件外部的选定框?

1 个答案:

答案 0 :(得分:1)

// include a value in your state defaults
this.state = {
  ...,
  submitDisabled: true
};

// update the value when a checkboxe's value changes
fieldNamesChanged = newFieldNames => {
    this.setState({
        ...,
        submitDisabled: !newFieldNames.length
    });
};

// use the state value to toggle the disabled property
<button
    ...
    disabled={this.state.submitDisabled}>
    Submit
</button>

Here's a demo