简体   繁体   English

React-table 隐藏按钮单击的各个列

[英]React-table hide various columns from button click

I have a react-table with a primary header containing multiple secondary headers underneath it.我有一个反应表,它的主标题包含多个辅助标题。 When the primary header is clicked I want all but one secondary header with name 'deposit' to be hidden, or shown (toggle).单击主标题时,我希望隐藏或显示(切换)名称为“存款”的所有辅助标题。 See screenshot.见截图。

I have a solution using column.toggleHeader(column.isVisible) .我有一个使用column.toggleHeader(column.isVisible)的解决方案。 I both wanted to demonstrate this as there wasn't a lot of material out there for how to do this;我都想证明这一点,因为那里没有很多关于如何做到这一点的材料; and I'm wondering if there are neater solutions using .getToggleHiddenProps .我想知道是否有使用.getToggleHiddenProps的更简洁的解决方案。 To be honest I don't understand what is going on with IndeterminateCheckbox eg.老实说,我不明白IndeterminateCheckbox发生了什么,例如。 https://github.com/TanStack/table/discussions/1989 and how that would be used with specific column header values. https://github.com/TanStack/table/discussions/1989以及如何将其与特定的列标题值一起使用。

在此处输入图像描述

My answer below.我的回答如下。

Just some background - this is a Web3 app that is getting information about Crypto wallets - hence why the code looks for '0x' and reduces the column header value to const headerShortened = header.substr(0,5) + '...' + header.substr(header.length - 4,header.length) (So 0x123abcFED1239876 becomes ox123...9876 )只是一些背景 - 这是一个 Web3 应用程序,它正在获取有关加密钱包的信息 - 因此代码查找“0x”并将列标题值减少为const headerShortened = header.substr(0,5) + '...' + header.substr(header.length - 4,header.length) (所以0x123abcFED1239876变成ox123...9876

I've just finished this initial version so don't AT me for any rough edges.我刚刚完成了这个初始版本,所以不要因为任何粗糙的边缘而攻击我。 Though happy to receive constructive feedback.虽然很高兴收到建设性的反馈。

interface DataTableProps {
    data: any
    columns: Column<DripRowFormat>[]
}

interface AHeaderProps {
    column: ColumnInstance<DripRowFormat>
    allColumns: Array<ColumnInstance<DripRowFormat>>
}

export function DataTable({data, columns}: DataTableProps) {

    const [hiddenColumns, setHiddenColumns] = useState<string[]>([])

    const initialState = {hiddenColumns}
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
        allColumns,
        getToggleHideAllColumnsProps,
        state
    } = useTable({columns, data, initialState});

    // console.log(`table input: ${JSON.stringify(data, null, 2)}`)
    // console.log(`table rows: ${Util.inspect(rows)}`)
    // console.log(`getTableProps: ${JSON.stringify(getTableProps())}`)
    // console.log(`allColumns: ${Util.inspect(allColumns)}`)

    const RenderHeader = ({column, allColumns}: AHeaderProps) => {
        const colHeaderClick = (e: React.MouseEvent<HTMLButtonElement>) => {
            e.preventDefault()
            // Now call column.toggleHidden() for all cols but 'deposit' - so when Hidden only Deposit is shown
            const childColumnsNotDeposit = allColumns.filter(c =>
                column.Header && c.Header && c.parent
                && c.Header.toString().toLowerCase() !== 'deposit'
                && c?.parent?.Header?.toString() === column.Header)
            childColumnsNotDeposit.forEach(c => {
                c.toggleHidden(c.isVisible)
            })
        }
    
        const drawHeaderWRTVisibleColumns = (column: ColumnInstance<DripRowFormat>): ReactNode => {
            if (! column) {
                return (
                    <span>NOT COL</span>
                )
            }
            const childCols = column.columns?.filter(c => c.isVisible)
            // @ts-ignore
            if (childCols && childCols.length < column?.columns?.length) {
                // @ts-ignore
                const header = column.Header.toString()
                const headerShortened = header.substr(0,5) +
                    '...' + header.substr(header.length - 4,header.length)
                return (
                    <span>{headerShortened}</span>
                )
            } else {
                return column.render('Header')
            }
        }
    
        // @ts-ignore
        if (column.placeholderOf?.Header.startsWith('0x')) {
            return (
                <button onClick={colHeaderClick}>{drawHeaderWRTVisibleColumns(column)}</button>
            )
        } else if (column.Header?.toString().startsWith('0x')) {
            return (
                <button onClick={colHeaderClick}>{drawHeaderWRTVisibleColumns(column)}</button>
            )
        } else {
            return (
                <span>{column.render('Header')}</span>
            )
        }
    }

    return (
        <div>
            <table {...getTableProps()}>
                <thead>
                    {headerGroups.map(headerGroup => (
                        <tr {...headerGroup.getHeaderGroupProps()}>
                            {headerGroup.headers.map(column => (
                                // @ts-ignore
                                <th {...column.getHeaderProps()}><RenderHeader column={column} allColumns={allColumns}/></th>
                            ))}
                        </tr>
                    ))}
                </thead>
                <tbody {...getTableBodyProps()}>
                    {rows.map((row, i) => {
                        prepareRow(row)
                        return (
                            <tr {...row.getRowProps()}>
                                {row.cells.map(cell => {
                                    return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                                })}
                            </tr>
                        )
                    })}
                </tbody>
            </table>
        </div>
    );
}




声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM