在 React.js 中滚动到页面顶部

在 React.js 中滚动到页面顶部

Scroll to the top of the Page in React.js

在 React 中使用window.scrollTo()滚动到页面顶部的方法,例如window.scrollTo(0, 0). 对象上的scrollTo方法window滚动到文档中的一组特定坐标。

应用程序.js
import {useEffect} from 'react'; export default function App() { useEffect(() => { // 👇️ scroll to top on page load window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }, []); return ( <div> <h2>Top of the page</h2> <div style={{height: '155rem'}} /> {/* 👇️ scroll to top on button click */} <button onClick={() => { window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }} style={{ position: 'fixed', padding: '1rem 2rem', fontSize: '20px', bottom: '40px', right: '40px', backgroundColor: '#0C9', color: '#fff', textAlign: 'center', }} > Scroll to top </button> </div> ); }

代码片段中的示例展示了如何:

  1. 渲染组件后滚动到页面顶部。
  2. 单击按钮滚动到页面顶部。

window.scrollTo
方法滚动到文档中的一组特定坐标

它所采用的对象的top属性指定沿Y轴滚动窗口的像素数。

The left property specifies the number of pixels to scroll the window on the
X axis.

The behavior property specifies whether the scrolling should animate smoothly (smooth), or happen instantly (auto).

The default value for the behavior property is auto.

You can use the
useEffect hook if you
need to scroll to the top of the page after the component renders.

We passed an empty dependencies array to the hook, so it’s only going to run on the initial render.

If you need to scroll to the top of the page when a button is clicked, set the
onClick prop on the element, passing it a function.

The function should call the window.scrollTo() method just like we did in the
useEffect hook.