在Redux Form中渲染material-ui-next Checkbox遇问题求助
我之前在把Redux Form和material-ui-next的Checkbox结合时也踩过坑,官方旧版示例确实不太适配新版组件。看你给出的代码片段,核心思路是对的,但还有几个细节可以调整,让组件能正确和Redux Form联动。
先给你一个完整的可运行实现:
import React from 'react'; import { Field, reduxForm } from 'redux-form'; import { FormGroup, FormControlLabel, Checkbox } from '@material-ui/core'; // 自定义Checkbox渲染组件 const renderCheckbox = ({ input, label, meta: { touched, error } }) => ( <FormGroup row> <FormControlLabel control={ <Checkbox checked={input.value || false} onChange={(event) => input.onChange(event.target.checked)} color="primary" /> } label={label} /> {touched && error && <span style={{ color: '#f44336', marginTop: 8, display: 'block' }}>{error}</span>} </FormGroup> ); // 主表单组件 const CheckboxForm = ({ handleSubmit, pristine, submitting }) => { return ( <form onSubmit={handleSubmit}> <Field name="termsAgreement" component={renderCheckbox} label="我已阅读并同意服务条款" /> <button type="submit" disabled={pristine || submitting} style={{ marginTop: 16 }} > 提交表单 </button> </form> ); }; // 用reduxForm包装表单,配置表单标识 export default reduxForm({ form: 'checkboxDemoForm' })(CheckboxForm);
这里几个关键调整点要注意:
- Checked状态的简化处理:不需要写
input.value ? true : false,直接input.value || false就能把undefined/null转换成布尔值,更简洁。 - 正确传递onChange事件:material-ui-next的Checkbox onChange返回的事件里,
event.target.checked才是我们需要的布尔值,直接把这个值传给input.onChange,Redux Form才能正确更新字段的状态。如果直接传event的话,Redux Form拿到的会是事件对象,不是布尔值,这会导致状态混乱。 - 去掉固定的value属性:你之前写的
value="checkedA"没必要保留,Redux Form会通过input.value来管理字段值,固定value会让组件状态和Redux存储的值不一致。 - 加入验证反馈:利用Redux Form提供的
meta对象,在用户触碰过组件且有错误时显示提示,这是表单组件很重要的一部分。
如果你的表单需要初始值,可以在reduxForm的配置里加initialValues,比如:
export default reduxForm({ form: 'checkboxDemoForm', initialValues: { termsAgreement: false // 默认未选中 } })(CheckboxForm);
这样调整后,Checkbox就能完美和Redux Form联动,状态同步也不会有问题了。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

