简体   繁体   English

如何使用React redux-form进行react-toggle?

[英]How to use react-toggle with React redux-form?

Is it possible to use react-toggle with Redux form? 是否可以使用Redux形式的react-toggle

react-toggle renders a toggle like so: react-toggle呈现如下切换:

<Toggle
  icons={false}
  onChange={this.handleToggleChange}
/>

Given a redux-form Field component like so: 给定一个redux-form Field组件,如下所示:

              <Field
                name="email_newsletter"
                id="email_newsletter"
                component="input"
                type="checkbox"
              />

How can react-toggle update the value for the redux-form Field? react-toggle如何更新redux-form字段的值?

在此输入图像描述

You can define a custom renderer like this: 您可以像这样定义自定义渲染器:

export const renderToggleInput = (field) => (
  <Toggle checked={field.input.value} onChange={field.input.onChange} icons={false} />
);

and set it to the component prop of the Field component: 并将其设置为Field组件的component prop:

<Field
    name="email_newsletter"
    id="email_newsletter"
    component={renderToggleInput}
/>

Warning: according to the value prop documentation , the value type need to be defined. 警告:根据值prop文档 ,需要定义value类型。

It will be a boolean for checkboxes, and a string for all other input types. 它将是复选框的布尔值,以及所有其他输入类型的字符串。 If there is no value in the Redux state for this field, it will default to ''. 如果此字段的Redux状态中没有值,则默认为''。 This is to ensure that the input is controlled. 这是为了确保输入受到控制。 If you require that the value be of another type (eg Date or Number), you must provide initialValues to your form with the desired type of this field. 如果您要求该值为其他类型(例如日期或数字),则必须为表单提供具有所需类型此字段的initialValues。

So you need to define also initial value for your checkbox in your redux-form. 因此,您需要在redux-form中为复选框定义初始值。

You will find more details in the Redux-Form Field documentation 您可以在Redux-Form Field文档中找到更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM