简体   繁体   English

结合 React 最终形式数组和最终形式计算

[英]Combining React Final Form Array and Final Form Calculate

I am having a really hard time accessing the objects within the field array for a calculated field price * quantity = total.我很难访问字段数组中的对象以计算字段价格 * 数量 = 总数。 Have tried a bunch of regex for the decorated field including field: /invoiceItems\[\d+\]/, to access and the solution from this PR ( https://github.com/final-form/final-form-calculate/pull/21/commits/dab00f8125079fed402712a4b0ed71663be0ba14 )已经为装饰字段尝试了一堆正则表达式,包括field: /invoiceItems\[\d+\]/,从这个 PR 访问和解决方案( https://github.com/final-form/final-form-calculate/拉/21/提交/dab00f8125079fed402712a4b0ed71663be0ba14

In the PR I cant access the index.在 PR 我无法访问索引。 What is the best way to do a calculation with final form calculate and arrays?用最终形式计算和 arrays 进行计算的最佳方法是什么? I have tried this in Formik as well but ran into the same issue.我也在 Formik 中尝试过,但遇到了同样的问题。

Code代码

Form:形式:

          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>

Field Array:字段数组:

                            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> 

Here is some of the Decorator I have tried.这是我尝试过的一些装饰器。 (Its a disaster with so many different attempts & ignore the math as we were just trying to get it to work) (这是一场灾难,有这么多不同的尝试&忽略数学,因为我们只是想让它工作)


    { 
      field: /invoiceItems\[\d+\]/ ,
      updates: {(name, index, value) => {
        [`invoiceItems[${index}].total`]: (_ignored, values) =>  2 
        //invoiceItems.total: (price, allValues) => price * 2
      }
    }
  )

Did end up fixing it based on this: How do I combine `final-form-calculate` with `final-form-array`最终是否基于此修复它: 如何将`final-form-calculate`与`final-form-array`结合起来

Here is the finished code:这是完成的代码:

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)),
      };
    },
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM