如何在Next.js中使用Bootstrap5?

安装 bootstrap 后,npm install bootstrap我添加了样式,/pages/_app.js如下所示:

import 'bootstrap/dist/css/bootstrap.css';
export default function App({ Component, pageProps }) {
    return <Component {...pageProps} />
}

然而,任何使用 javascript 的东西都不起作用,例如他们文档中的Collapse 示例。

function App() {
    return (
      <div>
        <p>
          <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
            Link with href
          </a>
          <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
            Button with data-bs-target
          </button>
        </p>
        <div class="collapse" id="collapseExample">
          <div class="card card-body">
            Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
          </div>
        </div>
      </div>
    );
}
export default App

如果我添加import 'bootstrap/dist/js/bootstrap.js'/pages/_app.js它会按预期开始“工作”,直到页面重新加载,其中显示ReferenceError: document is not defined (screenshot),这让我相信这是不可能的,或者我不应该尝试使用 boostrap + react 或 next.js。
我原以为他们放弃 jquery 意味着它应该可以“开箱即用”与像 react 这样的框架一起工作(因为不再需要 react-boostrap 或 reactstrap)

有没有办法正确使用 boostrap 5 和 nextjs?或者我应该完全尝试其他方法还是重新使用 reactstrap(目前似乎只支持 boostrap 4)?

回答

这是我们大多数人在切换到 NextJS 时错过的常见事情。

问题:文档未定义。

原因: NextJS 在服务器端渲染你的应用,服务器端没有窗口、文档等,因此document没有定义。你甚至console.log(typeof window, typeof document)可以验证这一点。

现在,解决方案是什么?

我在我的函数组件中使用了这段代码:

    useEffect(() => {
        typeof document !== undefined ? require('bootstrap/dist/js/bootstrap') : null
    }, [])

useEffect空的dependencies工作就像componentDidMount()在第二次运行代码后运行一样。由于代码首先在服务器上运行,然后在客户端运行,因此不会产生错误,因为客户端有文档。

我从来没有使用过`componentDidMount()。

这对我有用吗?

我刚刚Collapse example在我的其他应用程序中复制了您的内容来验证这一点。

  • Brilliant, thank you so much. Although for mine I had to add `import { useEffect } from 'react'`(else useeffect was undefined) at the top which I notice you don't have , is that correct? This is my entire `/pages/_app.js` now https://pastebin.com/raw/2qbEMxXp
  • @DavidPH 太棒了!您的 pastebin 代码立即生效,只是在我的默认 Next.js 应用程序 global.css 中拼写为“../styles/globals.css”。- 我还需要安装 popper 才能工作:`yarn add @popperjs/core`

以上是如何在Next.js中使用Bootstrap5?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>