如何通过id滚动到antd列表中的特定项目?

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

我在页面上显示了一个 antd 列表,其他地方的某些操作将导致列表中的项目被选择。我希望该项目自动滚动到它。我想不通。

显示列表的代码如下。

   <List
                            itemLayout="horizontal"
                            dataSource={courses}
                            className="hoverable-list"
                            bordered
                            renderItem={(item, index) => (
                                <List.Item bordered="true" className={currentCourse == item.course_code ? 'active' : ''} onClick={() => setCurrentCourse(item.course_code)}>
                                    {/* <Tooltip placement="bottomLeft" title={item.description}> */}
                                    <List.Item.Meta
                                        id={item.course_code}
                                        title={item.course_code}
                                        description={item.course_name}
                                    />
                                    {/* </Tooltip> */}
                                </List.Item>
                            )}
                        />

我尝试使用 getElementByID,然后将其滚动到视图中,但这似乎没有成功。

    const scrollToItem = (itemId) => {
        const element = document.getElementById(itemId);
      
        if (element) {
          element.scrollIntoView({ behavior: 'smooth' });
        }
      };

    const handleNodeClick = (nodeId) => {
        setCurrentCourse(nodeId);
        scrollToItem(nodeId);
    }
reactjs antd
1个回答
0
投票

您需要为列表创建一个可滚动的容器。在容器而不是 HTML 文档中滚动

例如

import { List } from 'antd';
import { useLayoutEffect } from 'react';

const data = [
  { id: '1', name: 'a' },
  { id: '2', name: 'b' },
  { id: '3', name: 'c' },
  { id: '4', name: 'd' },
  { id: '5', name: 'e' },
  { id: '6', name: 'f' },
  { id: '7', name: 'g' },
];

const scrollToItem = (itemId) => {
  const element = document.getElementById(itemId);

  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
};

export const App = () => {
  useLayoutEffect(() => {
    scrollToItem(3);
  }, []);

  return (
    <div
      id="scrollableDiv"
      style={{
        height: 200,
        overflow: 'auto',
        padding: '0 16px',
        border: '1px solid rgba(140, 140, 140, 0.35)',
      }}
    >
      <List
        dataSource={data}
        renderItem={(item) => (
          <List.Item id={item.id} key={item.id}>
            <List.Item.Meta
              title={<a href="https://ant.design">{item.name}</a>}
            />
            <div>Content</div>
          </List.Item>
        )}
      />
    </div>
  );
};

堆栈闪电战

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