从下拉列表中选择时使用参考滚动到做出反应

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

好的,我正在尝试创建一个下拉菜单,当选择一个项目时,页面应该滚动到特定部分(参考)。

我有几个具有相同引用的 div(因为我有超过 30 个需要引用的 div)。

const SettingView = () => {
    const selectedItem = "el2"; // This is temporarily as it will be the item from a dropdown
    const ref = useRef<HTMLDivElement[]>([]);
    const filterRef = (el: HTMLDivElement) => ref.current.push(el);

    return (
        <>
            <div ref={filterRef} id="el1">Some Text</div>
            <div ref={filterRef} id="el2">Some Text2</div>
            <div ref={filterRef} id="el3">Some Text3</div>
            <div ref={filterRef} id="el4">Some Text4</div>
            ....
        </>
    )
}

export default SettingView;

因此,单击按钮时,它应该找到具有来自 selectedItem 的 id 的 div 引用并滚动到它。

我该怎么做?

reactjs ref
1个回答
0
投票

您可以通过在所选元素的引用上使用scrollIntoView()方法来实现这一点。以下是您可以修改SettingView组件以实现此功能的方法:

import React, { useRef } from 'react';

const SettingView = () => {
    const selectedItem = "el2"; // This is temporarily as it will be the item from a dropdown
    const ref = useRef<HTMLDivElement[]>([]);
    const filterRef = (el: HTMLDivElement) => ref.current.push(el);

    const scrollToRef = (ref: React.RefObject<HTMLDivElement>, id: string) => {
        const selectedRef = ref.current.find(item => item.id === id);
        if (selectedRef) {
            selectedRef.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };

    // Call scrollToRef when selectedItem changes
    React.useEffect(() => {
        scrollToRef(ref, selectedItem);
    }, [selectedItem]);

    return (
        <>
            <div ref={filterRef} id="el1">Some Text</div>
            <div ref={filterRef} id="el2">Some Text2</div>
            <div ref={filterRef} id="el3">Some Text3</div>
            <div ref={filterRef} id="el4">Some Text4</div>
            {/* Add more divs as needed */}
        </>
    );
}

export default SettingView;

在此代码中: scrollToRef 函数采用 ref 数组和所选项目的 id。它找到具有匹配 id 的引用,并使用带有平滑行为选项的scrollIntoView()将其滚动到视图中并从块的开头开始。 useEffect 钩子用于每当 selectedItem 发生变化时触发滚动效果。

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