Material UI (Scrollspy) - React - 使用选项卡在列表中移动并自动滚动到索引

Material UI (Scrollspy) - React - use tabs to move through list and auto scroll to index

如果我有一个很大的项目列表,每个项目都有一个类别,

const categories: string[] = [0, 1, 2, 3, 4, 5];
const items: {name: string, category: number}[] = [{name: "foo", category: 1}, {name: "bar", category: 1}, {name: "foobar", category: 2}, {name: "barfoo", category: 3}, ... etc.];

..在 material-ui 中,它们被用作类别的选项卡 header:

  <AppBar>
    <Tabs
      value={tabIndex}
      onChange={handleChange}
      indicatorColor="secondary"
      variant="scrollable"
      scrollButtons="auto"
    >
      {categories.map((i) => (
        <Tab
          key={i}
          label={i}
        />
      ))}
    </Tabs>
  </AppBar>

然后我在选项卡 header 下得到了一长串项目,这些项目按类别分类在一起。

我如何通过自动滚动到基于选项卡 selected 的位置中的第一个类别以及在滚动到特定位置时自动更新选项卡位置来使用选项卡按顺序浏览列表列表中的第一个索引。

举个直观的例子:

Example image to use tabs to move through sequential content that needs to be read in a particular order

我怎样才能在 material ui 中实现这样的目标并做出反应?综上所述,

  1. 滚动浏览按类别排序的大量项目
  2. 自动滚动 到选项卡中的第一个列表位置类别 select
  3. 自动 select 基于列表滚动位置的选项卡

您要查找的组件是 material 的 Scrollspy and it is future component ui。

目前他们在 material ui 文档中实现了名为 AppTableOfContents 的组件。如果您在 right-hand-side 的文档中看到 Contents 部分。

https://github.com/mui-org/material-ui/issues/16359 在这里我找到了两个解决方案

  1. 使用react-scrollspy
  2. 使用useScrollspy Hook(试试这个)

上面是正确答案,但还有 this CodeSandbox example 也可以。