我怎样才能得到一个反应引导表中的一列的总和? ReactJS

时间:2018-10-18 12:12:08

标签: reactjs react-bootstrap-table

问题如下,我有一个从父亲那里接收道具的组件。问题是我知道如何获取到我的信息,但是我不能添加一列的总数。我曾尝试过_.sumby,但我认为我没有按要求使用它。

import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { connect } from 'react-redux';
import _ from 'lodash';

const formatName = (cell, row, extra) => {
  let display = 'No disponible'; if (_.get(row, 'name')) { display = `${_.get(row, 'name')}` }
  return (
    <div>
      {display}
    </div>
  )
};
const formatPrice = (cell, row, extra) => {
  let display = 0; if (_.get(row, 'total')) { display = `${_.get(row, 'total')}` }

  return (
    <div>
      {parseFloat(display).toFixed(2)}€
    </div>
  )
};



class ChartInventory extends React.Component {
  state = {
    sortName: 'name',
    sortOrder: 'asc',
  }

  render() {
    const options = {
      sortName: this.state.sortName,
      sortOrder: this.state.sortOrder
    };

    console.log('ANALYTICS ', this.props.analytics)
    return (
      <span>
        <BootstrapTable data={this.props.analytics}
          options={options}
          pagination={this.props.analytics.length > 50}
          trClassName="table-row"
          ref="inventoryAnalyticsTable">
          <TableHeaderColumn isKey={true} dataField='name' headerAlign='center' dataAlign='center' dataFormat={formatName} dataSort>Nombre</TableHeaderColumn>
          <TableHeaderColumn dataField='total' width='100' headerAlign='center' dataAlign='center' dataFormat={formatPrice}>Precio</TableHeaderColumn>
        </BootstrapTable>
        <div style={{ display: 'flex', flex: 1, flexDirection: 'column', alignItems: 'flex-end', marginRight: 10 }}>
          <div style={{ fontWeight: 'bold', justifyContent: 'center' }}>
            Precio Total
          </div>
          {_.sumBy(this.props.analytics, 'total').toFixed(2)}€
        </div>
      </span >
    );
  }
}

const mapStateToprops = state => ({
  analytics: state.inventory.analytics,
});

export default connect(mapStateToprops, null)(ChartInventory);

在这里您可以看到它

image link 我更喜欢使用页脚,但是我不知道如何对'total'列求和。 谢谢。

1 个答案:

答案 0 :(得分:-1)

您将在这里找到想要的东西(如果尚未找到的话):

https://react-bootstrap-table.github.io/react-bootstrap-table2/storybook/index.html?selectedKind=Footer&selectedStory=Function%20Footer&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Factions%2Factions-panel

TL; DR替代,您可以通过这种方式定义列并通过以下方式添加页脚信息:

const columns = [{
    dataField: 'name',
    text: 'Nombre',
    headerAlign: 'center',
    dataAlign='center',
    dataFormat={formatName},
    footer: columnData => columnData.reduce((acc, item) => acc + item, 0)
  }, {
    dataField: 'total',
    text: 'Precio',
    headerAlign: 'center',
    dataAlign='center',
    dataFormat={formatPrice},
    footer: columnData => columnData.reduce((acc, item) => acc + item, 0)
  }];

<BootstrapTable
  keyField="name"
  data={ this.props.analytics }
  columns={ columns }
/>