1

编辑 -

我在这里使用这个例子react-table select table (HOC)

只需在上述链接的示例代码中添加此代码即可提供我想要实现的结果。

  logSelection = () => {
    console.log('selection:', this.state.selection);
    this.setState({ selection: [] });
  }

背景

我在我的 React.js 应用程序中使用 react-table。具体来说,我正在使用选择表,它在每一行旁边提供了一个复选框。在我的情况下,这允许用户选择多行。一旦用户提交了他们的选择,他们选择的行中的数据就会被发送到我的应用程序中以供其他用途。

提交后,我正在清除处于状态的数据。这很重要,以防他们需要在之后直接进行另一次提交。在我从包含先前选择的每一行的状态数组中清除数据后,即使数据不再保存在状态数组中,表格仍会显示先前选择的行。

示例代码

这就是我清除包含所选数组的数组的方式,

  exportExcel() {
    this.setState({ selection: [], selectAll: false });
  }

这是类中的所有相关代码,

import React, {Component} from 'react';
import _ from 'lodash';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, FormGroup, Label, Input } from 'reactstrap';
import ReactTable from 'react-table';
import checkboxHOC from 'react-table/lib/hoc/selectTable';
import 'react-table/react-table.css';
import Chance from 'chance';
import { connect } from 'react-redux';
import { fetchOdx } from '../../store/actions/Odx';

const CheckboxTable = checkboxHOC(ReactTable);
const chance = new Chance();

class TypeAHead extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showRow: false,
      showExcelForm: false,
      modal: false,
      selection: [],
      selectAll: false,
      state: {},
      row: {},
      column: {},
      instance: {},
      data: [],
    };
    this.showRow = this.showRow.bind(this);
    this.showExcelForm = this.showExcelForm.bind(this);
    this.toggleSelection = this.toggleSelection.bind(this);
    this.toggleAll = this.toggleAll.bind(this);
    this.isSelected = this.isSelected.bind(this);
    this.exportExcel = this.exportExcel.bind(this);
    this.setClientEmail = this.setClientEmail.bind(this);

    this.props.fetchOdx();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.odxData) {
      this.setState({
        data: nextProps.odxData
      });
    }
  }

  showRow() {
    this.setState({
      showRow: !this.state.showRow
    });
  }

  showExcelForm() {
    this.setState({
      clientEmail: '',
      showExcelForm: !this.state.showExcelForm
    });
  }

  toggleSelection(key, shift, row) {
    let selection = [
      ...this.state.selection
    ];
    const keyIndex = selection.indexOf(key);
    if (keyIndex >= 0) {
      selection = [
        ...selection.slice(0, keyIndex),
        ...selection.slice(keyIndex + 1)
      ];
    } else {
      selection.push(row);
    }
    this.setState({ selection });
  }

  toggleAll() {
    const selectAll = this.state.selectAll ? false : true;
    const selection = [];
    if (selectAll) {
      const wrappedInstance = this.checkboxTable.getWrappedInstance();
      const currentRecords = wrappedInstance.getResolvedState().sortedData;
      currentRecords.forEach((item) => {
        selection.push(item._original._id);
      });
    }
    this.setState({ selectAll, selection });
  }

  isSelected(key) {
    this.state.selection.includes(key);
  }

  setClientEmail(event) {
    this.setState({ clientEmail: event.target.value.toLowerCase() });
  }

  exportExcel(event) {
    this.setState({ selection: [], selectAll: false });
    this.showExcelForm();
  }

  render() {
    const { toggleSelection, toggleAll, isSelected } = this;
    const { selectAll, } = this.state;
    const checkboxProps = {
      toggleSelection,
      toggleAll,
      isSelected,
      selectAll,
      selectType: 'checkbox',
    };
    const columns = [{
      Header: 'DebtCltRefNo',
      accessor: 'DebtCltRefNo'
    }, {
      Header: 'DbtrDebtorType',
      accessor: 'DbtrDebtorType',
    }];
    return (
      <div>
        <Button onClick={this.showExcelForm} color="success" size="lg" block>Export Excel</Button>
        <CheckboxTable
          data={this.state.data}
          columns={columns}
          className="-striped -highlight"
          defaultPageSize={10}
          ref={(r) => this.checkboxTable = r}
          filterable
          defaultFilterMethod={(filter, row) =>
            String(row[filter.id]) === filter.value}
          getTdProps={(state, row, column, instance) => ({
            onClick: e => {
              const r = row.original;
              this.setState({ state, row: r, column, instance });
              this.showRow();
            }})}
          {...checkboxProps}
        />
        <div>
          <Modal isOpen={this.state.showRow} toggle={this.showRow}>
            <ModalHeader toggle={this.showRow}>{this.state.row.DebtCltRefNo}</ModalHeader>
            <ModalBody>
              DbtrDebtorType: {this.state.row.DbtrDebtorType}<br />
              DebtType: {this.state.row.DebtType}<br />
            </ModalBody>
            <ModalFooter>
              <Button color="danger" onClick={this.toggle}>Cancel</Button>
            </ModalFooter>
          </Modal>
        </div>
        <div>
          <Modal isOpen={this.state.showExcelForm} toggle={this.showExcelForm}>
            <ModalHeader toggle={this.showExcelForm}>Grant Client Access</ModalHeader>
            <ModalBody>
              <Form>
                <FormGroup>
                  <Label for="clientEmail">Client's Email Address</Label>
                  <Input value={this.state.clientEmail} onChange={this.setClientEmail} type="email" name="clientEmail" id="clientEmail" placeholder="Client's Email Address" />
                </FormGroup>
              </Form>
            </ModalBody>
            <ModalFooter>
              <Button color="danger" onClick={this.showExcelForm}>Cancel</Button>
              <Button color="success" onClick={this.exportExcel}>Submit</Button>
            </ModalFooter>
          </Modal>
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  if (state.Odx.odx) {
    let data = state.Odx.odx;
    data = _.forEach([...data], (o) => o._id = chance.guid());
    return {
      odxData: data
    };
  } else {
    return {};
  }
};

const mapDispatchToProps = dispatch => ({
  fetchOdx: () => dispatch(fetchOdx()),
});

export default connect(mapStateToProps, mapDispatchToProps)(TypeAHead);

问题

提交表单后如何更新表格,以便没有选中任何行的复选框?或者换句话说,我怎样才能让表格与显示已选择行的状态数组一致?就我而言,在我将状态数组更新为空数组后,仍会在 UI 中选择所选行。

4

0 回答 0