在 Redux Form 中,如何设置复选框选中的 属性 的初始值?

In Redux Form, how can I set the initial value of the checked property of a checkbox?

在我们的 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
//  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 在安装 <input> 后立即变为 undefined。结果,当我的测试修改 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.

...除非我明确地将 <input> 上的 checked prop 设置为 false 而不是 undefined,如我上面发布的代码片段所示。

我想在测试 运行 之前设置 this.props.fields['checkbox'].checked 的初始值,而不是使用此 null 检查。 I know I can set the initial value of fields in Redux Form. 有没有办法像Redux Form也控制的checked 属性那样设置辅助属性的初始值?

我从未使用过 Redux-Form,但要在默认 React 中显示复选框的默认选中值,您需要使用 defaultChecked 属性。它接受一个布尔值。

<input type="checkbox" defaultChecked={/*bool*/} />

您可以在您的 checked 属性中创建一个简单的条件,以便当该值未定义时您只是 return false:

<input 
  type="checkbox" 
  checked={typeof this.props.fields['checkbox'].checked == 'undefined'?false:this.props.fields['checkbox'].checked} 
  onClick={() => {... your onClick code ...}} />

复选框与文本输入没有区别。您仍然可以将字段对象解构为 <input>。查看 employed 值如何在 v5.3.3 Simple Form Example.

中使用
<input type="checkbox" {...myField}/>

Redux Form 将检测到它是一个复选框(实际上它检测到 boolean 值)并使用 checked 属性。