当前位置:首页 > React

react 实现滚动

2026-01-26 15:26:44React

滚动到指定元素

使用 useRefscrollIntoView 方法可以滚动到页面中的特定元素。在 React 中创建一个 ref 并将其附加到目标元素上,通过调用 scrollIntoView 实现滚动效果。

import { useRef } from 'react';

function ScrollToElement() {
  const targetRef = useRef(null);

  const scrollToTarget = () => {
    targetRef.current.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <div>
      <button onClick={scrollToTarget}>Scroll to Target</button>
      <div style={{ height: '1000px' }}></div>
      <div ref={targetRef}>Target Element</div>
    </div>
  );
}

滚动到顶部/底部

通过 window.scrollTo 方法可以实现页面整体滚动到顶部或底部。结合 smooth 行为参数可以让滚动过程更流畅。

react 实现滚动

function ScrollToTop() {
  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const scrollToBottom = () => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  };

  return (
    <div>
      <button onClick={scrollToTop}>Scroll to Top</button>
      <button onClick={scrollToBottom}>Scroll to Bottom</button>
      <div style={{ height: '2000px' }}></div>
    </div>
  );
}

自定义滚动容器

对于非窗口滚动(如 div 容器内的滚动),需要使用容器的 scrollTop 属性。通过 ref 获取容器元素并控制其滚动位置。

import { useRef } from 'react';

function CustomScrollContainer() {
  const containerRef = useRef(null);

  const scrollToMiddle = () => {
    const container = containerRef.current;
    container.scrollTo({
      top: container.scrollHeight / 2,
      behavior: 'smooth'
    });
  };

  return (
    <div>
      <button onClick={scrollToMiddle}>Scroll to Middle</button>
      <div 
        ref={containerRef}
        style={{ 
          height: '300px', 
          overflow: 'auto',
          border: '1px solid #ccc'
        }}
      >
        <div style={{ height: '900px' }}>Scrollable Content</div>
      </div>
    </div>
  );
}

滚动事件监听

通过 useEffect 添加和移除滚动事件监听器,可以响应页面滚动行为并执行相应操作。

react 实现滚动

import { useEffect, useState } from 'react';

function ScrollListener() {
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div style={{ height: '2000px' }}>
      <div style={{ position: 'fixed', top: '20px', left: '20px' }}>
        Current Scroll Position: {scrollY}px
      </div>
    </div>
  );
}

滚动位置恢复

在页面导航时保持滚动位置,可以使用 useLayoutEffect 在组件挂载时恢复之前保存的滚动位置。

import { useLayoutEffect } from 'react';
import { useLocation } from 'react-router-dom';

function ScrollRestoration() {
  const location = useLocation();
  const scrollPositions = useRef({});

  useLayoutEffect(() => {
    const key = location.pathname;
    const savedPosition = scrollPositions.current[key];

    if (savedPosition !== undefined) {
      window.scrollTo(0, savedPosition);
    }

    return () => {
      scrollPositions.current[key] = window.scrollY;
    };
  }, [location]);
}

无限滚动加载

结合 Intersection Observer API 实现无限滚动加载更多内容的效果。

import { useState, useEffect, useRef } from 'react';

function InfiniteScroll() {
  const [items, setItems] = useState(Array(20).fill(0));
  const loaderRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        setItems(prev => [...prev, ...Array(10).fill(0)]);
      }
    });

    if (loaderRef.current) {
      observer.observe(loaderRef.current);
    }

    return () => observer.disconnect();
  }, []);

  return (
    <div>
      {items.map((_, i) => (
        <div key={i} style={{ height: '100px', border: '1px solid #eee' }}>
          Item {i + 1}
        </div>
      ))}
      <div ref={loaderRef}>Loading more...</div>
    </div>
  );
}

标签: react
分享给朋友:

相关文章

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何同步

react如何同步

React 同步状态管理方法 在 React 中实现同步状态管理,可以通过以下多种方式实现: 使用 useState 和 useEffect 钩子 通过 useState 定义状态,使用 useEf…

如何安装react

如何安装react

安装React的方法 方法一:使用Create React App(官方推荐) Create React App是官方提供的脚手架工具,适合快速搭建React项目。确保已安装Node.js(建议版本≥…

react路由如何配置

react路由如何配置

React 路由配置方法 安装 React Router 使用 npm 或 yarn 安装 React Router 的 DOM 版本: npm install react-router-dom #…

如何实操react

如何实操react

安装 React 环境 使用 create-react-app 快速搭建项目: npx create-react-app my-app cd my-app npm start 项目启动后默认在…