我真的很难访问字段数组中的对象,因为计算出的字段价格*数量=总数。我尝试了一堆正则表达式用于修饰字段,包括要访问的field: /invoiceItems\[\d+\]/ ,和来自此PR的解决方案(https://github.com/final-form/final-form-calculate/pull/21/commits/dab00f8125079fed402712a4b0ed71663be0ba14)
在PR中,我无法访问索引。使用final form calculate和数组进行计算的最佳方法是什么?我也在Formik中尝试过,但遇到了同样的问题。
代码
表格:
onSubmit={onSubmit}
decorators={[calculator]}
mutators={{
...arrayMutators,
}}
initialValues={{
companyName: "",
companyAddress: "",
companyCity: "",
companyState: "",
companyZip: "",
invoiceNumber: shortid.generate(),
invoicePaymentStatus: "",
invoiceStatus: "",
invoiceItems: [
],
invoiceDate: new Date(),
invoiceDueDate: new Date(
new Date().getTime() + 7 * 24 * 60 * 60 * 1000
),
clientFname: "",
clientLname: "",
billingAddress: "",
billingCity: "",
billingState: "",
billingZip: "",
propertyAddress: "",
propertyCity: "",
propertyState: "",
propertyZip: "",
invoiceTotal: "",
tax: "",
}}
render={({
handleSubmit,
reset,
submitting,
pristine,
values,
form: {
mutators: { push, pop },
},
}) => (
<form onSubmit={handleSubmit} noValidate>字段数组:
type="button"
onClick={() => push("invoiceItems", undefined)}
>
Add Line Item
</button>
<FieldArray name="invoiceItems">
{({ fields }) =>
fields.map((item, index) => (
<div key={item}>
<Field
name={`${item}.description`}
component={TextField}
placeholder="Description"
/>
<Field
name={`${item}.price`}
component={TextField}
placeholder="Price"
/>
<Field
name={`${item}.quantity`}
component={TextField}
placeholder="Quantity"
/>
<Field
name={`${item}.total`}
component={TextField}
placeholder="Total"
/>
<span
onClick={() => fields.remove(index)}
style={{ cursor: "pointer" }}
>
❌
</span>
</div>
))
}
</FieldArray> 这是我试过的一些装饰品。(这是一场灾难,有这么多不同的尝试&忽略数学,因为我们只是试图让它工作)
{
field: /invoiceItems\[\d+\]/ ,
updates: {(name, index, value) => {
[`invoiceItems[${index}].total`]: (_ignored, values) => 2
//invoiceItems.total: (price, allValues) => price * 2
}
}
)发布于 2020-04-17 18:44:25
最终基于此修复了它:How do I combine final-form-calculate with final-form-array
下面是完成的代码:
const calculator = createDecorator(
{
field: /invoiceItems\[\d+\]\.price/,
updates: (value, name, allValues) => {
const totalField = name.replace(".price", ".total");
const quantityField = name.replace(".price", ".quantity");
return {
[totalField]: parseInt(value) * parseInt(getIn(allValues, quantityField)),
};
},
},
{
field: /invoiceItems\[\d+\]\.quantity/,
updates: (value, name, allValues) => {
const totalField = name.replace(".quantity", ".total");
const priceField = name.replace(".quantity", ".price");
return {
[totalField]: parseInt(value) * parseInt(getIn(allValues, priceField)),
};
},
}
);https://stackoverflow.com/questions/61260785
复制相似问题