簡體   English   中英

如何在 React 中滾動到所需的元素?

[英]How to scroll to the desired element in React?

我有一個問題 - 我有一個列表,它位於一個高度有限的單獨彈出窗口中。 在這個高度之后,會出現一個側卷軸。 渲染該組件時,我需要自動滾動到特定元素。 如何實施? 我只是不知道如何滾動到某個元素。

下面是我的 jsx 代碼示例

<ul className={style.list}>
        {itemsForRender?.length ? (
          itemsForRender.map((item) => (
            <li className={style.item} key={item.id}>
              <button
                type="button"
                className={
                  activeItem === item.id
                    ? `${style.button} ${style.activeClass}`
                    : style.button
                }
                onClick={() => selectItem(item.id)}
              >
                {item.name}
              </button>
            </li>
          ))
        ) : (
          <p className={style.searchSubtitle}>
            Just text
          </p>
        )}
      </ul>

使用此代碼:

 const ScrollDemo = () => { const myRef = useRef(null) const executeScroll = () => myRef.current.scrollIntoView() // run this function from an event handler or an effect to execute scroll return ( <> <div ref={myRef}>Element to scroll to</div> <button onClick={executeScroll}> Click to scroll </button> </> ) }

我在 React 中使用了 Element.scrollIntoView() 方法來引用我想要滾動到的元素,這里是示例:

function TestComponent() {
  const testRef = useRef(null);
  const scrollToElement = () => testRef.current.scrollIntoView();
  // Once the scrollToElement function is run, the scroll will show the element
  return (
    <>
      <div ref={testRef}>Element you want to view</div>
      <button onClick={scrollToElement}>Trigger the scroll</button>
    </>
  );
}

你可以在你想自動滾動的地方使用scrollIntoView()

document.getElementById(element-id).scrollIntoView({behavior: 'smooth'})

您可以在useEffect()中使用它來在渲染組件時運行它

我希望這會有所幫助。 謝謝

const scrollRef = useRef([]);

useEffect(() => {
      // here you call the function scrollToSection and pass the id where you want to scroll
    }, [])

const scrollToSection = id => {
  if (scrollRef.current.length) {
    scrollRef.current[id].scrollIntoView();
  }
};

<ul className={style.list}>
  {itemsForRender?.length ? (
    itemsForRender.map((item) => (
      <li className={style.item} ref={ref => (scrollRef.current[item.id] = ref)} key={item.id}>
        <button
          type="button"
          className={
            activeItem === item.id
              ? `${style.button} ${style.activeClass}`
              : style.button
          }
          onClick={() => selectItem(item.id)}
        >
          {item.name}
        </button>
      </li>
    ))
  ) : (
    <p className={style.searchSubtitle}>
      Just text
    </p>
  )}
</ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM