我如何使用 react-sortable-hoc (Table) 自动滚动?

How do I AutoScroll with react-sortable-hoc (Table)?

我一直在努力实现 react-sortable-hoc 示例页面中提到的 this example,特别是 table 中的自动滚动行为。不幸的是,它看起来好像源代码不在存储库的示例目录中。

虽然我在下面的 codesandbox 中实现的代码是一个非常简单的示例,但我已经为此倾注了几个小时,使用 useWindowAsScrollContainergetContainer 以及 refs,但似乎什么都没有解决问题。

就是说,这是我注意到的行为:滚动出容器时,甚至滚动出 window 时,自动滚动功能永远不会启用。我什至求助于返回 document.bodygetContainer 这应该限制容器,但似乎无法复制 the repository's example.

中所述的行为

此外,虽然我在 SortableTable 组件上指定了固定的高度和宽度,理想情况下应该用 <AutoSizer /> 包裹,但暂时删除它以消除任何副作用.

https://codesandbox.io/s/mysortabletable-zi94g?file=/MySortableTable.js

您需要向 Sortable 组件提供容器,在使用第 3 方库使用 getContainer 属性进行渲染时,它必须限制 sortableElement

根据 react-sortable-hoc 文档:

getContainer is an Optional function to return the scrollable container element. This property defaults to the SortableContainer element itself or (if useWindowAsScrollContainer is true) the window. Use this function to specify a custom container object (eg this is useful for integrating with certain 3rd party components such as FlexTable). This function is passed a single parameter (the wrappedInstance React element) and it is expected to return a DOM element.

现在,由于您无法将直接引用传递给子项,因此您可以在 Table 组件上编写一个小包装器,然后再将其传递给 HOC

const MyTable = ({ tableRef, ...rest }) => {
    return <Table ref={this.props.tableRef} {...rest} />;
}
const SortableTable = SortableContainer(MyTable);
const SortableTableRowRenderer = SortableElement(defaultTableRowRenderer);

/**
 * Define the table schema
 */
const schema = [
  { dataKey: "col1", label: "Column 1" },
  { dataKey: "col2", label: "Column 2" }
];

/**
 * Generate row data according to the schema above
 * @param {*} rowCount
 */
function generateRows(rowCount) {
  const rows = [];
  for (let i = 0; i < rowCount; i++) {
    rows.push({ col1: i, col2: i * i });
  }
  return rows;
}

class MySortableTable extends Component {
  state = {
    schema,
    rows: generateRows(200)
  };

  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(({ rows }) => ({
      rows: arrayMove(rows, oldIndex, newIndex)
    }));
  };

  rowRenderer = props => {
    return <SortableTableRowRenderer {...props} />;
  };

  getRow = ({ index }) => {
    const { rows } = this.state;
    return rows[index];
  };

  render() {
    const { rows, schema } = this.state;

    return (
      <SortableTable
        width={500}
        height={500}
        headerHeight={32}
        rowHeight={32}
        tableRef={ref => (this.tableRef = ref)}
        getContainer={() => ReactDOM.findDOMNode(this.tableRef.Grid)}
        rowCount={rows.length}
        rowGetter={this.getRow}
        onSortEnd={this.onSortEnd}
        rowRenderer={this.rowRenderer}
      >
        {schema.map(col => (
          <Column {...col} key={col.dataKey} width={100} />
        ))}
      </SortableTable>
    );
  }
}

Working demo