简体   繁体   中英

Material-UI + React: Why doesn't <Table/>'s onRowSelection work for Select All?

Using Material-UI's <Table/> ( http://www.material-ui.com/#/components/table ) with ReactJS, I have a table set up with a select all checkbox. Every time a checkbox for a row is clicked on individually, the row id gets adds to the state array clickedRowIds . So console.log() , prints out an array with the ids of the clicked on row/s.

For example, if I were to check off the checkboxes just for the first row and second, the console log would print: ____THESE ARE THE CLICKED ROWS____ [1, 2] (With 1 and 2 representing the row ID numbers in integer). But when I click on the Select All checkbox in the header, it checks off all the checkboxes in the table, yet in the console.log() , it just shows ____THESE ARE THE CLICKED ROWS____ all and ids.forEach() gets an error Uncaught TypeError: ids.forEach is not a function .

The row checkboxes are all being clicked on via Select All checkbox, but why aren't all the row ID numbers being added to the clickedRowIds array? Using ids.forEach() , I would like to console log all the selected rows using Select All button.

export default class TestTable extends Component {
  constructor(props) {
    super(props)

    this.state = {
      clickedRowIds: [],
    }

    this.handleRowSelection = this.handleRowSelection.bind(this);
  }

  handleRowSelection(rowIds) {
    this.setState({
      clickedRowIds: rowIds
    })
  }

  render(){
    const ids = this.state.clickedRowIds
    console.log('____THESE ARE THE CLICKED ROWS____ ', ids)

    ids.forEach(id => {console.log(id)})

    return(

      <div className='table_body' style={styles.content}>
        <Table
          multiSelectable={true}
          onRowSelection={this.handleRowSelection}
        >
          <TableHeader
            displaySelectAll={true}
            enableSelectAll={true}
          >
              ...
          </TableHeader>
        </Table>
      </div>
    )
  }
}

Answer will be upvoted and answered.

Check the docs here: http://www.material-ui.com/#/components/table

Called when a row is selected. selectedRows is an array of all row selections. IF all rows have been selected, the string "all" will be returned instead to indicate that all rows have been selected.

This means that if all rows are selected, annoyingly, your rowIds will no longer be set to an array, but a string saying "all". You'll need some logic to handle that case before calling forEach on rowIds. Your error is due to the string "all" not having the forEach method available.

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