自动滚动与react-sortable-hoc(表)。

问题描述 投票:5回答:1

我一直在努力实现 本例 中指出 react-sortable-hoc 例子页面,特别是表格中的自动滚动行为。不幸的是,看起来源代码并不在版本库的examples目录下。

虽然我在下面的codesandbox中实现的代码是一个非常简单的例子,但我已经在这个问题上倾注了几个小时的心血,用了 useWindowAsScrollContainergetContainer 但似乎没有办法解决这个问题。

说到这里,我注意到的行为是:当从容器中滚动出去,甚至从窗口中滚动出去时,自动滚动功能从未启动。我甚至采取了返回 document.bodygetContainer 应该会限制容器,但似乎无法复制在 仓库的例子.

另外,虽然我在 "我的 "上指定了一个固定的高度和宽度,但我还是在 "我的 "上指定了一个固定的高度和宽度。SortableTable 组件,理想的情况下,应该用 <AutoSizer />但为了消除任何副作用,暂时删除。

https:/codesandbox.iosmysortabletable-zi94g?file=MySortableTs。

  • react-sortable-hoc: 1.11.0
  • react-virtualized: 9.7.5

enter image description here

javascript reactjs react-virtualized react-sortable-hoc
1个回答
2
投票

你需要为Sortable组件提供容器,它必须对其进行限制。sortableElement 当使用第三方库进行渲染时,使用 getContainer 支持。

根据 react-sortable-hoc 文档。

getContainer 是一个可选函数,用于返回可滚动容器元素。这个属性默认为 SortableContainer 元素本身或 useWindowAsScrollContainer 是true)的窗口。使用这个函数来指定一个自定义的容器对象(例如,这对于集成某些第三方组件如FlexTable很有用)。这个函数被传递了一个单一的参数(wrappedInstance React元素),并且它被期望返回一个DOM元素。

现在,由于你不能直接传递一个ref给子元素,你可以在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>
    );
  }
}

工作演示

© www.soinside.com 2019 - 2024. All rights reserved.