我正在努力构建下面的redux-form以收集用户输入的电子邮件。这些字段应该都具有相同的名称=“email”
问题是当组件呈现时,我聚焦并键入一个字段时,所有字段立即使用第一个输入字段中的最新值更新。所有这三个领域似乎都捆绑在了一起。
使用redux-form,如何让表单具有相同名称的输入?
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import {connect} from 'react-redux';
class InvitePage extends React.Component {
handleSubmit(data) {
console.log(data)
}
render() {
return (
<div>
<h1>Invites</h1>
<form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))}>
<div>
<label>Email address</label>
<div>
<Field
name="email"
component="input"
type="email"
placeholder="Email"
/>
</div>
<div>
<Field
name="email"
component="input"
type="email"
placeholder="Email"
/>
</div>
<div>
<Field
name="email"
component="input"
type="email"
placeholder="Email"
/>
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
);
}
}
InvitePage = reduxForm({
form: 'InvitePage'
})(InvitePage);
export default InvitePage;
答案 0 :(得分:6)
如果您使用FieldArray
而不是3 Field
,它可以处理为每个字段生成redux-form状态的唯一名称,并且您可以使用硬编码的渲染器(或允许您使用覆盖)name
字段到你想要的任何东西,因为redux-form为每个字段生成一个onChange
处理程序,无论你为name
属性呈现什么,它都会更新正确的状态。
这是一个显示实际行动的例子:
相关代码段:
// For the sake of this example, we're hard-coding the name to 'email'
let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
<div>
<label>{label}</label>
<div>
<input {...input} name="email" type="email"/>
{touched && error && <span>{error}</span>}
</div>
</div>
let renderEmails = ({fields, meta: {submitFailed, error}}) =>
<ul>
<li>
<button type="button" onClick={() => fields.push()}>Add Email</button>
</li>
{fields.map((email, index) =>
<li key={index}>
{index > 2 && <button
type="button"
title="Remove Email"
onClick={() => fields.remove(index)}
/>}
<Field
name={email}
component={renderEmailField}
label={`Email #${index + 1}`}
/>
</li>
)}
{submitFailed && error && <li className="error">{error}</li>}
</ul>
let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
<form onSubmit={handleSubmit}>
<FieldArray name="emails" component={renderEmails} />
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
EmailsForm = reduxForm({
form: 'emailsForm',
// Provide 3 initial values to show 3 email fields
initialValues: {
emails: ['', '', '']
}
})