如何在react js中使用onClick滚动div?

han*_*nah -2 reactjs

大家好,我是 ReactJS 的新人。

我想滚动特定的 div 而不是窗口

          const handleScroll = (event) => {
      window.scrollBy(100, 0);
      }
Run Code Online (Sandbox Code Playgroud)

Pul*_*epa 10

您可以使用useRefhook 来引用您想要使用 React 功能组件滚动的组件。然后用于scrollIntoView提供平滑的滚动行为。

这是一个例子:

import React, { useRef } from "react";

export default function App() {
const titleRef = useRef();

function handleClick() {
  titleRef.current.scrollIntoView({ behavior: "smooth" });
}

return (
  <article>
    <h1 ref={titleRef}>A React article for Latin readers</h1>
    Here is the content
    <br />
    <button onClick={handleClick}>Back to the top</button>
  </article>
);
}
Run Code Online (Sandbox Code Playgroud)