当前位置:首页 > 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 native

如何评价react native

React Native 的优势 跨平台开发效率高:基于 JavaScript 和 React 语法,可同时开发 iOS 和 Android 应用,减少重复代码量。性能接近原生:通过原生组件渲染,性能…

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app np…

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

如何手写一个react

如何手写一个react

手写一个简单的 React 创建一个基础的 React 实现需要理解其核心概念:虚拟 DOM、组件、状态管理和渲染。以下是一个简化版的 React 实现。 创建虚拟 DOM 虚拟 DOM 是真实…

react如何更新

react如何更新

更新 React 版本的方法 检查当前 React 版本 运行以下命令查看项目中安装的 React 版本: npm list react 更新 React 及相关依赖 通过 npm 或 yarn…