带有自创建输入的 Redux 表单 [英] Redux form with self creating inputs

查看:36
本文介绍了带有自创建输入的 Redux 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以动态创建自己的输入的 redux 表单(使用 redux-form).我无法弄清楚如何让 redux-form 了解已创建的新字段.是否可以在表单组件本身中动态更改 redux-form 传入的 fields 属性?我在想这个错误吗?这是我正在使用的.

class AddCustomer 扩展组件 {使成为() {类形式扩展组件{构造函数(道具,上下文){超级(道具,上下文)this.state = {输入添加:[]};}句柄添加输入(){让inputsToAdd = this.state.inputsToAdd.slice();inputToAdd.push(this.state.inputsToAdd.length);this.setState({ inputToAdd });}提交表单(数据){控制台日志(数据)this.setState({inputsToAdd: []});this.props.dispatch(initialize('addCustomer', {}))}使成为() {const { 字段,handleSubmit } = this.props;返回 (<div><form onSubmit={handleSubmit(this.submitForm.bind(this))}><Input type='text' label='Company name' {...fields['companyName']}/><Input type='email' label='Admin user email' {...fields['adminEmail']}/></表单>{this.state.inputsToAdd.map((element, index) => {返回 (<输入键={index} type='text'/>)})}<Button onClick={() =>this.handleAddInput()}>添加输入<Button onClick={handleSubmit(this.submitForm.bind(this))}>提交</Button>

)}}表单 = connectReduxForm({形式:'添加客户',字段:['公司名称','adminEmail']})(形式);返回 (<div><h1>添加客户</h1><表格/>

)}}

解决方案

从 Redux Form 6.* 开始,您可以使用 <FieldArray/>

实现您想要做的事情>

见下面的例子(取自 Redux 文档并稍微简化)

从 'react' 导入 Reactimport { Field, FieldArray, reduxForm } from 'redux-form'从'./validate'导入验证const renderMembers = ({ fields, meta: { touch, error } }) =>(<ul><li><button type="button" onClick={() =>fields.push({})}>添加成员</button>{感动&&错误&&<span>{错误}</span>}{fields.map((member, index) =><li key={index}><按钮类型=按钮"标题="删除成员"onClick={() =>fields.remove(index)}/><h4>成员#{index + 1}</h4><字段name={`${member}.firstName`}类型=文本"组件={renderField}标签=名字"/><字段name={`${member}.lastName`}类型=文本"组件={renderField}标签=姓氏"/>)})const FieldArraysForm = (props) =>{const { handleSubmit,提交} = props返回 (<form onSubmit={handleSubmit}><FieldArray name="members" 组件={renderMembers}/><div><button type="submit" disabled={submitting}>提交</button>

</表单>)}导出默认 reduxForm({form: 'fieldArrays',//此表单的唯一标识符证实})(FieldArraysForm)

有关更多信息,请查看文档http://redux-form.com/6.1.1/examples/fieldArrays/

I'm trying to create a redux form (using redux-form) that can dynamically create it's own inputs. I am having trouble figuring out how to make redux-form aware of the new fields that have been created. Is it possible to dynamically change the fields prop that redux-form passes in within the form component itself? Am I thinking about this wrong? Here is what I am working with.

class AddCustomer extends Component {

 render() {

  class Form extends Component {

    constructor(props, context) {
      super(props, context)
      this.state = {
        inputsToAdd: []
      };
    }

    handleAddInput() {
       let inputsToAdd = this.state.inputsToAdd.slice();
       inputsToAdd.push(this.state.inputsToAdd.length);
       this.setState({ inputsToAdd });
    }

    submitForm(data) {
       console.log(data)
       this.setState({inputsToAdd: []});
       this.props.dispatch(initialize('addCustomer', {}))
    }

    render() {
      const { fields, handleSubmit } = this.props;
      return (
          <div>
            <form onSubmit={handleSubmit(this.submitForm.bind(this))}>
              <Input type='text' label='Company name' {...fields['companyName']}/>
              <Input type='email' label='Admin user email' {...fields['adminEmail']}/>
            </form>
            {this.state.inputsToAdd.map((element, index) => {
              return (
                <Input key={index} type='text' />
              )
            })}
            <Button onClick={() => this.handleAddInput()}>Add Input</Button>
            <Button onClick={handleSubmit(this.submitForm.bind(this))}>Submit</Button>
          </div>
        )
      }
    }

    Form = connectReduxForm({
      form: 'addCustomer',
      fields: ['companyName', 'adminEmail']
    })(Form);

    return (
      <div>
        <h1>Add Customer</h1>
        <Form />
      </div>
    )
  }
}

As of Redux Form 6.* you can achieve what you are trying to do using <FieldArray/>

See the example below (taken from Redux documentation and slightly simplified)

import React from 'react'
import { Field, FieldArray, reduxForm } from 'redux-form'
import validate from './validate'

const renderMembers = ({ fields, meta: { touched, error } }) => (
  <ul>
    <li>
      <button type="button" onClick={() => fields.push({})}>Add Member</button>
      {touched && error && <span>{error}</span>}
    </li>
    {fields.map((member, index) =>
      <li key={index}>
        <button
          type="button"
          title="Remove Member"
          onClick={() => fields.remove(index)}/>
        <h4>Member #{index + 1}</h4>
        <Field
          name={`${member}.firstName`}
          type="text"
          component={renderField}
          label="First Name"/>
        <Field
          name={`${member}.lastName`}
          type="text"
          component={renderField}
          label="Last Name"/>

      </li>
    )}
  </ul>
)


const FieldArraysForm = (props) => {
const { handleSubmit, submitting } = props
  return (
    <form onSubmit={handleSubmit}>
      <FieldArray name="members" component={renderMembers}/>
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'fieldArrays',     // a unique identifier for this form
  validate
})(FieldArraysForm)

For more info checkout the documentation http://redux-form.com/6.1.1/examples/fieldArrays/

这篇关于带有自创建输入的 Redux 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆