2018-06-22T15:02:11Z||2018-06-22T15:08:10Z


不支持全选全部页面,艹。干他。

代码(用rowSelection的onSelectAll和onSelectInvert解决):

import React from 'react';
import { Table } from 'antd';

export default class MyList extends React.Component {
  static cols = [{
    title: 'ID',
    dataIndex: 'id',
  }, {
    title: 'Name',
    dataIndex: 'name',
  }]

  constructor(props) {
    super(props);

    // 这里存的是初始的选择状态
    const { selectedItems } = props;
    // 把初始状态转换成id, 因为初始选择可能是一堆objects, 但是selectedRowKeys要的是IDs
    this.state = {
      selectedRowKeys: selectedItems ? selectedItems.map(s => s.id) : [],
    };
  }

  render() {
    const { dataSource } = this.props;
    const { selectedRowKeys } = this.state;

    // 在这里创建rowSelection
    const rowSelection = {
      selectedRowKeys,
      // 注意onChange不要丢掉,艹
      onChange: this.handleChange,
      onSelectAll: this.handleSelectAll,
    };

    return (
      <Table
        columns={MyList.cols}
        dataSource={dataSource}
        rowKey="id"
        rowSelection={rowSelection}
      />
    );
  }

  handleChange = (selectedRowKeys, selectedRows) => {
    const { onSelectionChange } = this.props;
    // 这里记住设置state
    this.setState({
      selectedRowKeys,
    });
    // bubble up events
    if (onSelectionChange) {
      onSelectionChange(selectedRows);
    }
  }
  
  // 全选 所有页面
  handleSelectAll = (selected) => {
    if (selected) {
      this.handleChange((this.props.dataSource || []).map(s => s.id), this.props.dataSource);
    } else {
      this.handleChange([], []);
    }
  }
}

{ true}