reactjs - 如何将react-toggle与React redux-form一起使用?

标签 reactjs redux-form react-redux-form react-toggle

是否可以使用react-toggle与 Redux 形式?

react-toggle 渲染一个切换,如下所示:

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

给定一个像这样的 redux-form Field 组件:

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

react-toggle 如何更新 redux-form 字段的值?

enter image description here

最佳答案

您可以像这样定义自定义渲染器:

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

并将其设置为 Field 组件的 component 属性:

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

警告:根据value prop documentation ,需要定义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 ''. This is to ensure that the input is controlled. If you require that the value be of another type (e.g. Date or Number), you must provide initialValues to your form with the desired type of this field.

因此,您还需要在 redux-form 中为复选框定义初始值。

您可以在 Redux-Form Field documentation 中找到更多详细信息

关于reactjs - 如何将react-toggle与React redux-form一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45651907/

相关文章:

reactjs - 如何在表单渲染后预填充 "redux form' s"输入字段

javascript - Simple-todos 应用程序教程,尝试创建一个从 Mongo 集合中删除已检查任务的函数

javascript - 在 ReactJS 中,在迭代非浅层数据结构时如何最好地组织我的代码

reactjs - 为什么 `npm test` 只进行一项测试就需要这么长时间?

redux-form - 我可以在表单提交时禁用 redux 表单的异步验证吗?

javascript - 使用 props.change 更改 redux-form 中输入字段的值

javascript - React 路由器匹配路径问题

reactjs - nextjs13 中所有 mui 组件上的 'use client' 是什么?

javascript - 测试 redux 表单失败 - typeError formProps.handleSubmit 不是函数

javascript - 如何避免无用的mapStateToProps()?