Antd Table:如何以编程方式确保行可见?

Antd Table: How programmatically ensure row visible?

使用 Ant Design Table,我如何以编程方式滚动(我正在使用 scroll:y)一行到视图中,因为它是行键以确保它可见?

选项 1:

使用document.querySelector('div.ant-table-body').scrollTop = rowIndex * 50

如果行高为 stable,示例用法 55px

检查工作stackblitz

(见antd问题 滚动到虚拟 table 行 )

class App extends React.Component {
  handleScroll = () => {
    document.querySelector('div.ant-table-body').scrollTop = 20 * 55;
  };

  render() {
    return (
      <div>
        <p>
          <Button type="primary" onClick={this.handleScroll}>
            Scroll
          </Button>
        </p>
        <Table
          columns={columns}
          dataSource={data}
          pagination={{ pageSize: 50 }}
          scroll={{ y: 240 }}
        />
      </div>
    );
  }
}

选项 2:

将第三方库 scroll-into-viewrowClassName 一起使用。

附上支票codesandbox and the corresponding antd issue Scroll the table to the specified row

import React from 'react';
import { render } from 'react-dom';
import 'antd/dist/antd.css';
import { Table, Button } from 'antd';
import scrollIntoView from 'scroll-into-view';

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    width: 150,
  },
  {
    title: 'Address',
    dataIndex: 'address',
  },
];

const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i,
    name: `Edward King ${i}`,
    age: 32,
    address: `London, Park Lane no. ${i}`,
  });
}

class App extends React.Component {
  handleScroll = () => {
    scrollIntoView(document.querySelector('.scroll-row'), {
      align: {
        top: 0,
      },
    });
  }

  render() {
    return (
      <div>
        <p>
          <Button type="primary" onClick={this.handleScroll}>Scroll</Button>
        </p>
        <Table
          rowClassName={(record, index) => (index === 20 ? 'scroll-row' : '')}
          columns={columns}
          dataSource={data}
          pagination={{ pageSize: 50 }}
          scroll={{ y: 240 }}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

以防万一它有用,如果您有更改当前选择的依赖项,这里是按键查找行和滚动的 TS 代码:

useEffect(() => {
        const rows = document.querySelector('.your-antd-table')
                      ?.getElementsByClassName('ant-table-row');
        if (!rows) return;
        const myRowKey = f(stuffNeededToFindYourRowKey);
        const target = _.find(rows, 
            r => r.getAttribute('data-row-key') === myRowKey);
        if (!target) return;
        scrollIntoView(target as HTMLElement);
    }, [stuffNeededToFindYourRowKey])