Kev*_*ica 5 javascript reactjs redux redux-form
在我们的 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}
/>
);
Run Code Online (Sandbox Code Playgroud)
}
如评论中所述,在我的测试环境中,this.props.field['checkbox'].checked是undefined在安装<input>. 结果,当我的测试修改 的值时this.props.field['checkbox'].checked,我收到以下警告:
警告:申请人表单正在更改要控制的复选框类型的不受控制的输入。输入元素不应从不受控制切换到受控制(反之亦然)。决定在组件的生命周期内使用受控或非受控输入元素。
......除非我明确设置的checked道具上<input>,以false代替undefined,如代码片断展示我张贴以上。
我想this.props.fields['checkbox'].checked在测试运行之前设置初始值,而不是使用此空检查。我知道我可以在 Redux 表单中设置字段的初始值。有没有办法设置辅助属性的初始值,比如checkedRedux Form 也控制的属性?
您可以在检查的属性中创建一个简单的条件,以便当该值未定义时您只需返回 false:
<input
type="checkbox"
checked={typeof this.props.fields['checkbox'].checked == 'undefined'?false:this.props.fields['checkbox'].checked}
onClick={() => {... your onClick code ...}} />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9111 次 |
| 最近记录: |