Select row on click react-table

后端 未结 7 923
广开言路
广开言路 2020-12-08 06:29

I am trying to find the best table to use with my react apps, and for now, the react-table offers everything I need (pagination, server-side control, filtering, sorting, foo

7条回答
  •  醉话见心
    2020-12-08 07:10

    There is a HOC included for React-Table that allows for selection, even when filtering and paginating the table, the setup is slightly more advanced than the basic table so read through the info in the link below first.




    After importing the HOC you can then use it like this with the necessary methods:

    /**
    * Toggle a single checkbox for select table
    */
    toggleSelection(key: number, shift: string, row: string) {
        // start off with the existing state
        let selection = [...this.state.selection];
        const keyIndex = selection.indexOf(key);
    
        // check to see if the key exists
        if (keyIndex >= 0) {
            // it does exist so we will remove it using destructing
            selection = [
                ...selection.slice(0, keyIndex),
                ...selection.slice(keyIndex + 1)
            ];
        } else {
            // it does not exist so add it
            selection.push(key);
        }
        // update the state
        this.setState({ selection });
    }
    
    /**
    * Toggle all checkboxes for select table
    */
    toggleAll() {
        const selectAll = !this.state.selectAll;
        const selection = [];
    
        if (selectAll) {
            // we need to get at the internals of ReactTable
            const wrappedInstance = this.checkboxTable.getWrappedInstance();
            // the 'sortedData' property contains the currently accessible records based on the filter and sort
            const currentRecords = wrappedInstance.getResolvedState().sortedData;
            // we just push all the IDs onto the selection array
            currentRecords.forEach(item => {
                selection.push(item._original._id);
            });
        }
        this.setState({ selectAll, selection });
    }
    
    /**
    * Whether or not a row is selected for select table
    */
    isSelected(key: number) {
        return this.state.selection.includes(key);
    }
    
     (this.checkboxTable = r)}
        toggleSelection={this.toggleSelection}
        selectAll={this.state.selectAll}
        toggleAll={this.toggleAll}
        selectType="checkbox"
        isSelected={this.isSelected}
        data={data}
        columns={columns}
    />
    

    See here for more information:
    https://github.com/tannerlinsley/react-table/tree/v6#selecttable

    Here is a working example:
    https://codesandbox.io/s/react-table-select-j9jvw

提交回复
热议问题