我有一个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
属性来解决此问题,还是需要跟踪此组件外部的选定框?
答案 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>