首页 > 解决方案 > 当 React-Table (v6) Tree Table 段打开时,如何运行函数?

问题描述

我正在使用React Table (version 6)

我的表正在使用Tree Table HoC

树表 hoc 示例

当其中一个树表段打开时,我需要运行一些代码。我不知道该怎么做。

是否有捷径可寻?

标签: reactjsreact-table

解决方案


关键是onExpandedChange道具。

const toArray = iterable => [].slice.call(iterable)

const Table = () => {
    const $tableWrapper = useRef()

    const getGroupFromIndexPath = indexPath => {
        return indexPath.reduce(($parentElem, index) => {
            return toArray($parentElem.children).filter($child => $child.classList.contains('rt-tr-group'))[index]
        }, $tableWrapper.current.querySelector('.rt-tbody'))
    }

    return (
        <div ref={$tableWrapper}>
            <ReactTable
                data={data}
                columns={columns}
                pivotBy={['name']}
                // I have no idea what the 1st parameter value is supposed to represent:/
                onExpandedChange={(value1, indexPath, event, rowData) => {
                    const $parentGroup = getGroupFromIndexPath(indexPath)
                    const $childGroup = $parentGroup.querySelector('.rt-tr-group')

                    if ($childGroup) {
                        // The expander is open
                    } else {
                        // The expander is closed
                    }
                }}
            />
        </div>
    )
}

推荐阅读