在我们的 Redux Form 5.3(不是 6.x)应用程序中,我想渲染一个 <input type="checkbox" />
像这样:
// In some cases, fieldHelper.checked is initially undefined. Then, when the
// user clicks one of the checkboxes, fieldHelper.checked is
// explicitly set to true or false. This change from one of the component's
// props being undefined to having a value causes a React warning; see
// http://stackoverflow.com/a/38015169/473792 and
// https://facebook.github.io/react/docs/forms.html#controlled-components
// So to prevent that warning, we do a quick null check on
// fieldHelper.checked and replace it with false explicitly if it is
// undefined before rendering the checkbox.
const fieldHelper = this.props.field['checkbox'];
const checked = fieldHelper.checked || false;
const modifiedFieldHelper = Object.assign({}, fieldHelper);
delete modifiedFieldHelper.checked;
return (
<input
checked={checked}
{...modifiedFieldHelper}
/>
);
如评论中所述,在我的测试环境中,this.props.field['checkbox'].checked
是undefined
安装 <input>
后立即.结果,当我的测试修改了 this.props.field['checkbox'].checked
的值时,我收到以下警告:
Warning: ApplicantForm is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
...除非我明确设置 checked
prop在 <input>
上至 false
而不是 undefined
,如我上面发布的代码片段所示。
我想设置 this.props.fields['checkbox'].checked
的初始值,而不是使用此空检查。在我的测试运行之前。 I know I can set the initial value of fields in Redux Form.有没有办法设置辅助属性的初始值,如 checked
Redux Form 也控制的属性?
最佳答案
您可以在您的 checked 属性中创建一个简单的条件,以便当该值未定义时您只返回 false:
<input
type="checkbox"
checked={typeof this.props.fields['checkbox'].checked == 'undefined'?false:this.props.fields['checkbox'].checked}
onClick={() => {... your onClick code ...}} />
关于javascript - 在 Redux Form 中,如何设置复选框的选中属性的初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452053/