代码之家  ›  专栏  ›  技术社区  ›  gyosifov

单击“反应表”时选择行

  •  60
  • gyosifov  · 技术社区  · 7 年前

    react-table 提供我需要的一切(分页、服务器端控制、过滤、排序、页脚行)。

    尽管如此,我似乎无法选择一行。没有 examples

    e 也没有 t 此外,我不喜欢这种方法,因为这不是react应用程序应该做的事情。

    <ReactTable
                ...
                getTrProps={(state, rowInfo, column, instance) => {
                    return {
                        onClick: (e, t) => {
                            t.srcElement.classList.add('active')
                        },
                        style: {
                        }
                    }
                }}
            />
    

    我错过房间里的大象了吗?如果没有,你知道另一个库支持我前面描述的东西吗?

    非常感谢。

    Davorin Ruevljan在评论中建议的另一件事是,但我无法使其生效:

    onRowClick(e, t, rowInfo) {
        this.setState((oldState) => {
            let data = oldState.data.slice();
            let copy = Object.assign({},  data[rowInfo.index]);
    
            copy.selected = true;
            copy.FirstName = "selected";
            data[rowInfo.index] = copy;
    
            return {
                data: data,
            }
        })
    }
    
    ....
    
                getTrProps={(state, rowInfo, column) => {
                    return {
                        onClick: (e, t) => { this.onRowClick(e, t, rowInfo) },
                        style: {
                            background: rowInfo && rowInfo.row.selected ? 'green' : 'red'
                        }
                    }
                }}
    

    这会将“FirstName”列设置为“selected”,但不会将类设置为“green”

    9 回复  |  直到 6 年前
        1
  •  78
  •   Emeeus    5 年前

    <ReactTable> 组件:

    getTrProps={(state, rowInfo) => {
      if (rowInfo && rowInfo.row) {
        return {
          onClick: (e) => {
            this.setState({
              selected: rowInfo.index
            })
          },
          style: {
            background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
            color: rowInfo.index === this.state.selected ? 'white' : 'black'
          }
        }
      }else{
        return {}
      }
    }
    

    在你的 state 不要忘记添加null selected

    state = { selected: null }
    
        2
  •  19
  •   halsdunes Alex    5 年前

    React表中包含一个HOC,允许进行选择,即使在对表进行筛选和分页时,设置也比基本表略高级,因此请先阅读下面链接中的信息。


    enter image description here



    导入HOC后,您可以像这样使用它,并使用必要的方法:

    /**
    * 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);
    }
    
    <CheckboxTable
        ref={r => (this.checkboxTable = r)}
        toggleSelection={this.toggleSelection}
        selectAll={this.state.selectAll}
        toggleAll={this.toggleAll}
        selectType="checkbox"
        isSelected={this.isSelected}
        data={data}
        columns={columns}
    />
    

    请参阅此处了解更多信息:
    https://github.com/tannerlinsley/react-table/tree/v6#selecttable

    下面是一个工作示例:
    https://codesandbox.io/s/react-table-select-j9jvw

        3
  •  4
  •   ThunderBird NoeXWolf    6 年前

    如果没有,可以使用您已有的代码安装onCLick处理程序。现在,您可以修改状态,而不是尝试将样式直接附加到行,例如将“选定:true”添加到行数据。这将触发重播。现在,您只需覆盖如何渲染选定==true的行。大致如下:

    // Any Tr element will be green if its (row.age > 20) 
    <ReactTable
      getTrProps={(state, rowInfo, column) => {
        return {
          style: {
            background: rowInfo.row.selected ? 'green' : 'red'
          }
        }
      }}
    />
    
        4
  •  3
  •   Jun Bin    6 年前

    import React from 'react';
    import ReactTable from 'react-table';
    import 'react-table/react-table.css';
    import { ReactTableDefaults } from 'react-table';
    import matchSorter from 'match-sorter';
    
    
    class ThreatReportTable extends React.Component{
    
    constructor(props){
      super(props);
    
      this.state = {
        selected: [],
        row: []
      }
    }
    render(){
    
      const columns = this.props.label;
    
      const data = this.props.data;
    
      Object.assign(ReactTableDefaults, {
        defaultPageSize: 10,
        pageText: false,
        previousText: '<',
        nextText: '>',
        showPageJump: false,
        showPagination: true,
        defaultSortMethod: (a, b, desc) => {
        return b - a;
      },
    
    
      })
    
        return(
        <ReactTable className='threatReportTable'
            data= {data}
            columns={columns}
            getTrProps={(state, rowInfo, column) => {
    
    
            return {
              onClick: (e) => {
    
    
                var a = this.state.selected.indexOf(rowInfo.index);
    
    
                if (a == -1) {
                  // this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
                  this.setState({selected: [...this.state.selected, rowInfo.index]});
                  // Pass props to the React component
    
                }
    
                var array = this.state.selected;
    
                if(a != -1){
                  array.splice(a, 1);
                  this.setState({selected: array});
    
    
                }
              },
              // #393740 - Lighter, selected row
              // #302f36 - Darker, not selected row
              style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},
    
    
            }
    
    
            }}
            noDataText = "No available threats"
            />
    
        )
    }
    }
    
    
      export default ThreatReportTable;
    
        5
  •  3
  •   andres aguirre gonzalez    6 年前

    您选择的答案是正确的,但是如果您使用的是排序表,它将崩溃,因为在搜索时rowInfo将变得未定义,建议改用此函数

                    getTrGroupProps={(state, rowInfo, column, instance) => {
                        if (rowInfo !== undefined) {
                            return {
                                onClick: (e, handleOriginal) => {
                                  console.log('It was in this row:', rowInfo)
                                  this.setState({
                                      firstNameState: rowInfo.row.firstName,
                                      lastNameState: rowInfo.row.lastName,
                                      selectedIndex: rowInfo.original.id
                                  })
                                },
                                style: {
                                    cursor: 'pointer',
                                    background: rowInfo.original.id === this.state.selectedIndex ? '#00afec' : 'white',
                                    color: rowInfo.original.id === this.state.selectedIndex ? 'white' : 'black'
                                }
                            }
                        }}
                    }
    
        6
  •  1
  •   nick    2 年前

    如果您使用的是最新版本(当时为7.7),则可以使用 toggleRoWSelected()

    <tr
      {...row.getRowProps()}
      className="odd:bg-white even:bg-gray-100"
      onClick={() => row.toggleRowSelected()}
    >
      {row.cells.map((cell) => {
        return (
          <td {...cell.getCellProps()} className="p-2">
            {cell.render("Cell")}
          </td>
        );
      })}
    </tr>;
    
    
        7
  •  0
  •   eric gilbertson    7 年前

    动态样式的另一种机制是在JSX中为组件定义它。例如,以下内容可用于选择性地设置React-tic-tac-toe教程中当前步骤的样式(建议的额外信用增强之一):

      return (
        <li key={move}>
          <button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    

        8
  •  0
  •   JackTheKnife    5 年前

    带有复选框的多行,并使用全选 useState() 挂钩。需要少量实施以适应自己的项目。

        const data;
        const [ allToggled, setAllToggled ] = useState(false);
        const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
        const [ selected, setSelected ] = useState([]);
    
        const handleToggleAll = allToggled => {
            let selectAll = !allToggled;
            setAllToggled(selectAll);
            let toggledCopy = [];
            let selectedCopy = [];
            data.forEach(function (e, index) {
                toggledCopy.push(selectAll);
                if(selectAll) {
                    selectedCopy.push(index);
                }
            });
            setToggled(toggledCopy);
            setSelected(selectedCopy);
        };
    
        const handleToggle = index => {
            let toggledCopy = [...toggled];
            toggledCopy[index] = !toggledCopy[index];
            setToggled(toggledCopy);
            if( toggledCopy[index] === false ){
                setAllToggled(false);
            }
            else if (allToggled) {
                setAllToggled(false);
            }
        };
    
    ....
    
    
                    Header: state => (
                        <input
                            type="checkbox"
                            checked={allToggled}
                            onChange={() => handleToggleAll(allToggled)}
                        />
                    ),
                    Cell: row => (
                        <input
                            type="checkbox"
                            checked={toggled[row.index]}
                            onChange={() => handleToggle(row.index)}
                        />
                    ),
    
    ....
    
    <ReactTable
    
    ...
                        getTrProps={(state, rowInfo, column, instance) => {
                            if (rowInfo && rowInfo.row) {
                                return {
                                    onClick: (e, handleOriginal) => {
                                        let present = selected.indexOf(rowInfo.index);
                                        let selectedCopy = selected;
    
                                        if (present === -1){
                                            selected.push(rowInfo.index);
                                            setSelected(selected);
                                        }
    
                                        if (present > -1){
                                            selectedCopy.splice(present, 1);
                                            setSelected(selectedCopy);
                                        }
    
                                        handleToggle(rowInfo.index);
                                    },
                                    style: {
                                        background: selected.indexOf(rowInfo.index)  > -1 ? '#00afec' : 'white',
                                        color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
                                    },
                                }
                            }
                            else {
                                return {}
                            }
                        }}
    />
    
        9
  •  0
  •   Shiva Vivek    3 年前
    # react-table with edit button #
    const [rowIndexState, setRowIndexState] = useState(null);
    const [rowBackGroundColor, setRowBackGroundColor] = useState('')
    {...row.getRowProps({
      onClick: (e) => {
        if (!e.target.cellIndex) {
           setRowIndexState(row.index);
           setRowBackGroundColor('#f4f4f4')
        }
      },
      style: {
       background: row.index === rowIndexState ? rowBackGroundColor : '',
      },              
    })}
    
    推荐文章