我有一个使用react-final-form-array
的表单,以便有很多"与会者"。我希望每个Attendee.Email输入都进行Web查找,然后根据结果设置Attendee.FirstName和Attendee.Surname。
我不确定如何使用final-form-calculate
装饰器表达这一点。具体来说,我不知道如何引用数组中的单个表单项。
这是我作为一个开始所得到的:
const MyForm = props => {
const calculator = createDecorator(
{
field: 'Attendees.Email', // <-- this needs to happen for each Email
updates: {
// ... do some lookups and set FirstName and Surname based off database query
Attendees.FirstName: (email, allValues) =>
someLookup(email).FirstName
}
},
);
const submit = values => {
console.log(values);
};
return (<Form onSubmit={submit}
mutators={{
...arrayMutators,
}}
decorators={[calculator]}
render={({handleSubmit, pristine, invalid, mutators: {push, pop}}) => {
return (
<form onSubmit={handleSubmit}>
<fieldset>
<legend>Attendees</legend>
<div className="fieldset">
<p><Button bsStyle="primary" onClick={() => push('Attendees', undefined)}>
Add attendee
</Button></p>
<FieldArray name="Attendees">
{({fields}) =>
fields.map((name, index) => (
<div key={name}>
<label>Attendee #{index + 1} {index > 0 && <span
onClick={() => {
const attendee = fields.remove(index);
}}
style={{cursor: 'pointer'}}
role="img"
aria-label="delete">❌</span>}</label>
<Field
name={`${name}.Email`}
component={TextField}
label="Email address"
validate={required}
/>
<Field
name={`${name}.FirstName`}
component={TextField}
label="First name"
validate={required}
/>
<Field
name={`${name}.Surname`}
component={TextField}
label="Surname"
validate={required}
/>
</div>
))}
</FieldArray>
</div>
</fieldset>
<Button type="submit" bsStyle="primary"
disabled={invalid}>Next</Button>
</form>
);
}}
/>);
};
export default MyForm;
答案 0 :(得分:4)
从the website i noticed they have it listed (but not clearly)
开始,我有点狩猎,但实际上非常简单所以对于我的情况,我只是拿起了名字并更改了文本的最后部分以反映我想要修改的对象属性。
下面,我使用正则表达式匹配一个字段,然后替换名称值的最后一部分以匹配不同的字段(存储在fieldName中),然后返回一个包含我正在更改的新字段和新值的数组。 / p>
{
field: /fields\[\d+\]\.field\.text/, // when a field matching this pattern changes...
updates: (value, name, allValues) => {
console.log('Update called', value, name);
const fieldName = name.replace('.text', '.name');
return {
[fieldName]: value.replace(/\W+/gi, '-').toLowerCase()
};
}
}