首页 > 解决方案 > 总结反应

问题描述

我有一个显示值的表格。

我想添加一行,其中包含每列的总数。

const MyComponent = () => {
  <Grid item container md={6} direction="row">
    <Table
      className="seasonTable"
      toolbar={false}
      columns={[
        {
          field: "process",
          title: "Proceso",
          render: (row) => {
            return row.process;
          },
        },
        {
          field: "current_season",
          title: "Temporada actual (" + seasons[2].name + ")",
          render: (row) => {
            return row.season1;
          },
        },
        {
          field: "previuos_season",
          title: "Temporada anterior (" + seasons[1].name + ")",
          render: (row) => {
            return row.season2;
          },
        },
        {
          field: "two seasons ago",
          title: "Temporada anterior (" + seasons[0].name + ")",
          render: (row) => {
            return row.season3;
          },
        },
      ]}
      data={filterProcessData()}
    ></Table>
  </Grid>;
};

然后我如图所示显示表格。

/**
 * filterProcessData
 */
function filterProcessData() {
  /** @const filterData Array */
  const filterData = [];

  // Filter water foot print
  waterFootprintEvolution.forEach((item) => {
    // If specific process was selected then filter the others
    if (processSelected != "all" && processSelected.id != item.id) {
      return true;
    }

    // Attach data
    // @todo Modify data for the selected seasons
    filterData.push({
      process: item.name,
      season1: item.data[2].total,
      season2: item.data[1].total,
      season3: item.data[0].total,
    });
  });

  return filterData;
}

我对 React 完全陌生,但我必须做这个改变。

这就是我目前所做的工作,我想在每列的末尾添加总计。

![在此处输入图像描述 我怎样才能做到这一点?太感谢了。

标签: javascriptreactjssum

解决方案


Display sums of each column as last row:

Add an additonal total line to your filterData:

function filterProcessData() {
    const filterData = [];

    waterFootprintEvolution.forEach((item) => {
        ...
    });

    const total = { process: "Totals", season1: 0, season2: 0, season3: 0 };
    filterData.forEach(row => {
        total.season1 += row.season1;
        total.season2 += row.season2;
        total.season3 += row.season3;
    });
    filterData.push(total);
    return filterData;
}

Display sums of each row as last column:

Can't you just add a new column for your total:

{
    field: "total",
    title: "Total",
    render: row => {
        return row.total
    }
}

And add a new corresponding total field to the object which is pushed into filterData:

filterData.push ({
    process: item.name,
    season1: item.data[2].total,
    season2: item.data[1].total,
    season3: item.data[0].total,
    total: item.data[2].total + item.data[1].total + item.data[0].total
});

OR maybe this change to your columns is even enough (no extra field needed in filterData):

{
    field: "total",
    title: "Total",
    render: row => {
        return row.season1 + row.season2 + row.season3
    }
}

推荐阅读