You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

复制Bootstrap文档代码后Scrollspy在React项目中失效求助

React中Bootstrap Scrollspy导航高亮失效的解决方案

问题诊断

核心问题是Bootstrap Scrollspy的JavaScript功能未启用,同时滚动容器缺少固定高度设置,导致滚动事件无法被检测,最终导航项的.active类切换失效。

具体修复步骤

1. 安装并引入Bootstrap依赖的JavaScript组件

Bootstrap 5的Scrollspy依赖@popperjs/core和自身JS文件,你目前仅引入了CSS,缺失JS支持:

  • 安装依赖:
npm install @popperjs/core
  • 在index.js中添加Bootstrap JS引入:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import "bootstrap/dist/css/bootstrap.min.css";
// 新增Bootstrap JS引入
import "bootstrap/dist/js/bootstrap.bundle.min.js";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

reportWebVitals();

2. 给滚动容器设置固定高度

你的.scrollspy-example仅设置了overflow-y: scroll,但无固定高度,容器会自适应内容高度,不会出现滚动条,Scrollspy无法检测滚动行为。修改App.css:

.App {
  text-align: center;
}

.scrollspy-example {
  overflow-y: scroll;
  /* 添加固定高度,可按需调整 */
  height: 400px;
}

3. 手动初始化Scrollspy(解决React渲染时机问题)

由于React的DOM渲染机制,data属性的自动初始化可能失效,可在组件挂载后手动初始化:
修改App.js,添加useEffect:

import "./App.css";
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // 初始化Scrollspy实例
    const scrollContainer = document.getElementById('home');
    if (scrollContainer) {
      new window.bootstrap.ScrollSpy(scrollContainer, {
        target: '#navbar-example2',
        rootMargin: '0px 0px -40%',
        smoothScroll: true
      });
    }

    // 组件卸载时销毁实例,避免内存泄漏
    return () => {
      if (scrollContainer) {
        window.bootstrap.ScrollSpy.getInstance(scrollContainer)?.dispose();
      }
    };
  }, []);

  return (
    <div className="App">
      <nav id="navbar-example2" className="navbar bg-light px-3 mb-3">
        <a className="navbar-brand" href="#home">Navbar</a>
        <ul className="nav nav-pills">
          <li className="nav-item">
            <a className="nav-link" href="#scrollspyHeading1">First</a>
          </li>
          <li className="nav-item">
            <a className="nav-link" href="#scrollspyHeading2">Second</a>
          </li>
          {/* 补充对应内容的导航项,原代码内容存在但导航缺失 */}
          <li className="nav-item">
            <a className="nav-link" href="#scrollspyHeading3">Third</a>
          </li>
          <li className="nav-item">
            <a className="nav-link" href="#scrollspyHeading4">Fourth</a>
          </li>
          <li className="nav-item">
            <a className="nav-link" href="#scrollspyHeading5">Fifth</a>
          </li>
        </ul>
      </nav>
      <div
        id="home"
        data-bs-spy="scroll"
        data-bs-target="#navbar-example2"
        data-bs-root-margin="0px 0px -40%"
        data-bs-smooth-scroll="true"
        className="scrollspy-example bg-light p-3 rounded-2"
        tabIndex="0"
      >
        {/* 原内容保持不变 */}
        <h4 id="scrollspyHeading1">First heading</h4>
        <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Incidunt reiciendis voluptatibus molestiae neque cum quam odio sed tempora deleniti! Debitis dolores incidunt a alias saepe esse facere illo in unde?</p>
        <h4 id="scrollspyHeading2">Second heading</h4>
        <p>I'm baby shoreditch mlkshk whatever, next level fashion axe occupy PBR&B DSA disrupt blog heirloom scenester. Cliche snackwave flexitarian praxis master cleanse affogato mlkshk vexillologist subway tile swag vegan tofu tote bag tousled la croix. Vibecession coloring book salvia yr vape distillery hell of narwhal jianbing gochujang vinyl. Shaman normcore hoodie swag stumptown. Banh mi gastropub raclette austin lo-fi prism semiotics kitsch yuccie. Slow-carb affogato skateboard, pork belly everyday carry vegan put a bird on it scenester typewriter. Portland godard letterpress kogi four dollar toast knausgaard. Cliche stumptown chambray 90's chia, pabst beard small batch four loko hexagon glossier cloud bread disrupt occupy. Listicle adaptogen four loko art party typewriter yr. Vaporware synth mustache, chambray shaman DSA paleo hoodie farm-to-table poke. Gluten-free +1 umami yes plz celiac yuccie. Pabst subway tile XOXO enamel pin vice cold-pressed. Poke cardigan iceland artisan salvia bushwick neutra VHS twee cloud bread. Street art shoreditch narwhal, freegan pabst pickled DSA schlitz. Sustainable austin bitters marfa. Butcher activated charcoal street art fam portland asymmetrical. Polaroid man braid selfies organic yr. Vape squid put a bird on it kale chips vice biodiesel tumeric kitsch migas cronut everyday carry succulents. Neutra everyday carry mlkshk tbh, organic chartreuse keytar tacos church-key taxidermy typewriter 8-bit. YOLO wolf pitchfork plaid activated charcoal tofu. Ugh selfies chia bicycle rights fashion axe bitters, VHS cold-pressed fanny pack next level mlkshk fingerstache taxidermy. Banh mi selvage unicorn typewriter, next level taxidermy shaman authentic chartreuse waistcoat skateboard tilde humblebrag tacos small batch. Wayfarers four loko forage, selfies tumeric tbh snackwave same bodega boys authentic pinterest neutra vice. Pug gochujang meggings put a bird on it tumblr hexagon taiyaki. Lo-fi asymmetrical hammock authentic sus. Kale chips slow-carb hashtag, knausgaard artisan live-edge try-hard disrupt mixtape crucifix whatever butcher. Poutine gatekeep +1 selvage woke heirloom disrupt tousled echo park four loko pour-over XOXO etsy shoreditch. Locavore migas sustainable offal ugh echo park, fanny pack synth hoodie umami next level trust fund quinoa pinterest. 90's XOXO tousled enamel pin JOMO, tofu semiotics master cleanse.</p>
        <h4 id="scrollspyHeading3">Third heading</h4>
        <p>I'm baby shoreditch mlkshk whatever, next level fashion axe occupy PBR&B DSA disrupt blog heirloom scenester. Cliche snackwave flexitarian praxis master cleanse affogato mlkshk vexillologist subway tile swag vegan tofu tote bag tousled la croix. Vibecession coloring book salvia yr vape distillery hell of narwhal jianbing gochujang vinyl. Shaman normcore hoodie swag stumptown. Banh mi gastropub raclette austin lo-fi prism semiotics kitsch yuccie. Slow-carb affogato skateboard, pork belly everyday carry vegan put a bird on it scenester typewriter. Portland godard letterpress kogi four dollar toast knausgaard. Cliche stumptown chambray 90's chia, pabst beard small batch four loko hexagon glossier cloud bread disrupt occupy. Listicle adaptogen four loko art party typewriter yr. Vaporware synth mustache, chambray shaman DSA paleo hoodie farm-to-table poke. Gluten-free +1 umami yes plz celiac yuccie. Pabst subway tile XOXO enamel pin vice cold-pressed. Poke cardigan iceland artisan salvia bushwick neutra VHS twee cloud bread. Street art shoreditch narwhal, freegan pabst pickled DSA schlitz. Sustainable austin bitters marfa. Butcher activated charcoal street art fam portland asymmetrical. Polaroid man braid selfies organic yr. Vape squid put a bird on it kale chips vice biodiesel tumeric kitsch migas cronut everyday carry succulents. Neutra everyday carry mlkshk tbh, organic chartreuse keytar tacos church-key taxidermy typewriter 8-bit. YOLO wolf pitchfork plaid activated charcoal tofu. Ugh selfies chia bicycle rights fashion axe bitters, VHS cold-pressed fanny pack next level mlkshk fingerstache taxidermy. Banh mi selvage unicorn typewriter, next level taxidermy shaman authentic chartreuse waistcoat skateboard tilde humblebrag tacos small batch. Wayfarers four loko forage, selfies tumeric tbh snackwave same bodega boys authentic pinterest neutra vice. Pug gochujang meggings put a bird on it tumblr hexagon taiyaki. Lo-fi asymmetrical hammock authentic sus. Kale chips slow-carb hashtag, knausgaard artisan live-edge try-hard disrupt mixtape crucifix whatever butcher. Poutine gatekeep +1 selvage woke heirloom disrupt tousled echo park four loko pour-over XOXO etsy shoreditch. Locavore migas sustainable offal ugh echo park, fanny pack synth hoodie umami next level trust fund quinoa pinterest. 90's XOXO tousled enamel pin JOMO, tofu semiotics master cleanse.</p>
        <h4 id="scrollspyHeading4">Fourth heading</h4>
        <p>I'm baby shoreditch mlkshk whatever, next level fashion axe occupy PBR&B DSA disrupt blog heirloom scenester. Cliche snackwave flexitarian praxis master cleanse affogato mlkshk vexillologist subway tile swag vegan tofu tote bag tousled la croix. Vibecession coloring book salvia yr vape distillery hell of narwhal jianbing gochujang vinyl. Shaman normcore hoodie swag stumptown. Banh mi gastropub raclette austin lo-fi prism semiotics kitsch yuccie. Slow-carb affogato skateboard, pork belly everyday carry vegan put a bird on it scenester typewriter. Portland godard letterpress kogi four dollar toast knausgaard. Cliche stumptown chambray 90's chia, pabst beard small batch four loko hexagon glossier cloud bread disrupt occupy. Listicle adaptogen four loko art party typewriter yr. Vaporware synth mustache, chambray shaman DSA paleo hoodie farm-to-table poke. Gluten-free +1 umami yes plz celiac yuccie. Pabst subway tile XOXO enamel pin vice cold-pressed. Poke cardigan iceland artisan salvia bushwick neutra VHS twee cloud bread. Street art shoreditch narwhal, freegan pabst pickled DSA schlitz. Sustainable austin bitters marfa. Butcher activated charcoal street art fam portland asymmetrical. Polaroid man braid selfies organic yr. Vape squid put a bird on it kale chips vice biodiesel tumeric kitsch migas cronut everyday carry succulents. Neutra everyday carry mlkshk tbh, organic chartreuse keytar tacos church-key taxidermy typewriter 8-bit. YOLO wolf pitchfork plaid activated charcoal tofu. Ugh selfies chia bicycle rights fashion axe bitters, VHS cold-pressed fanny pack next level mlkshk fingerstache taxidermy. Banh mi selvage unicorn typewriter, next level taxidermy shaman authentic chartreuse waistcoat skateboard tilde humblebrag tacos small batch. Wayfarers four loko forage, selfies tumeric tbh snackwave same bodega boys authentic pinterest neutra vice. Pug gochujang meggings put a bird on it tumblr hexagon taiyaki. Lo-fi asymmetrical hammock authentic sus. Kale chips slow-carb hashtag, knausgaard artisan live-edge try-hard disrupt mixtape crucifix whatever butcher. Poutine gatekeep +1 selvage woke heirloom disrupt tousled echo park four loko pour-over XOXO etsy shoreditch. Locavore migas sustainable offal ugh echo park, fanny pack synth hoodie umami next level trust fund quinoa pinterest. 90's XOXO tousled enamel pin JOMO, tofu semiotics master cleanse.</p>
        <h4 id="scrollspyHeading5">Fifth heading</h4>
        <p>I'm baby shoreditch mlkshk whatever, next level fashion axe occupy PBR&B DSA disrupt blog heirloom scenester. Cliche snackwave flexitarian praxis master cleanse affogato mlkshk vexillologist subway tile swag vegan tofu tote bag tousled la croix. Vibecession coloring book salvia yr vape distillery hell of narwhal jianbing gochujang vinyl. Shaman normcore hoodie swag stumptown. Banh mi gastropub raclette austin lo-fi prism semiotics kitsch yuccie. Slow-carb affogato skateboard, pork belly everyday carry vegan put a bird on it scenester typewriter. Portland godard letterpress kogi four dollar toast knausgaard. Cliche stumptown chambray 90's chia, pabst beard small batch four loko hexagon glossier cloud bread disrupt occupy. Listicle adaptogen four loko art party typewriter yr. Vaporware synth mustache, chambray shaman DSA paleo hoodie farm-to-table poke. Gluten-free +1 umami yes plz celiac yuccie. Pabst subway tile XOXO enamel pin vice cold-pressed. Poke cardigan iceland artisan salvia bushwick neutra VHS twee cloud bread. Street art shoreditch narwhal, freegan pabst pickled DSA schlitz. Sustainable austin bitters marfa. Butcher activated charcoal street art fam portland asymmetrical. Polaroid man braid selfies organic yr. Vape squid put a bird on it kale chips vice biodiesel tumeric kitsch migas cronut everyday carry succulents. Neutra everyday carry mlkshk tbh, organic chartreuse keytar tacos church-key taxidermy typewriter 8-bit. YOLO wolf pitchfork plaid activated charcoal tofu. Ugh selfies chia bicycle rights fashion axe bitters, VHS cold-pressed fanny pack next level mlkshk fingerstache taxidermy. Banh mi selvage unicorn typewriter, next level taxidermy shaman authentic chartreuse waistcoat skateboard tilde humblebrag tacos small batch. Wayfarers four loko forage, selfies tumeric tbh snackwave same bodega boys authentic pinterest neutra vice. Pug gochujang meggings put a bird on it tumblr hexagon taiyaki. Lo-fi asymmetrical hammock authentic sus. Kale chips slow-carb hashtag, knausgaard artisan live-edge try-hard disrupt mixtape crucifix whatever butcher. Poutine gatekeep +1 selvage woke heirloom disrupt tousled echo park four loko pour-over XOXO etsy shoreditch. Locavore migas sustainable offal ugh echo park, fanny pack synth hoodie umami next level trust fund quinoa pinterest. 90's XOXO tousled enamel pin JOMO, tofu semiotics master cleanse.</p>
      </div>
    </div>
  );
}

export default App;

额外说明

如果后续尝试react-ui-scrollspy,直接按照其文档引入组件并绑定对应ID即可,这类React封装的组件会更适配React生命周期,避免原生Bootstrap JS的DOM同步问题。

内容的提问来源于stack exchange,提问作者Cflux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:19:32