简体   繁体   中英

Calculate total in dynamic form - Ant Design React

I have a dynamic form in Ant Design where I can:

  • set the price and the quantity in some inputs.
  • create new rows

I was able to access all the values from the rows after submiting with this piece of code:

  const onFinish = values => {
    console.log("Received values of form:", values);
  };

But I would like to access each value from the inputs, get the total (price * quantity) and set it the total input.

在此处输入图像描述

I saw a solution in basic React from this question Calculating quantity and price total in react . That answer shows that you need use state and use the onChange event and work from there, but I don't really know how to translate this answer because I don't understand how to access the state from each row in Ant Design.

You can see my code right here: https://codesandbox.io/s/stupefied-hawking-pcr7k?file=/index.js:260-348

Any help would be appreciated

You can calculate derived values by taking advantage of the onValuesChange event handler on the Form component, and the form instance methods provided by the Form.useForm hook.

Please see sandbox example:

https://codesandbox.io/s/antdesign-calculating-a-derived-value-using-dynamic-form-hgyzh?file=/index.js:229-1020

const ItemForm = () => {
  const [form] = Form.useForm()
  const onFinish = values => {
    console.log('Received values of form:', values)
  }

  const handleTotal = (_, values) => {
    const rowsCopy = [...values.rows]
    values.rows.forEach((fieldGroup, index) => {
      if (fieldGroup && fieldGroup.quantity && fieldGroup.price) {
        fieldGroup.total = fieldGroup.quantity * fieldGroup.price
        rowsCopy.splice(index, 1, fieldGroup)
        console.log('fieldGroup', fieldGroup)
        console.log('rowsCopy', rowsCopy)
        form.setFieldsValue({ rows: rowsCopy })
      }
    })
  }

  return (
    <Form
      name="dynamic_form_nest_item"
      form={form}
      onFinish={onFinish}
      onValuesChange={handleTotal}
      autoComplete="off"
      size="small"
    >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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