这是我第一次使用 Next JS,我正在尝试引导 Next JS 应用程序,直到现在我必须使用 bootstrap 的 Javascript 来进行轮播。
所以首先,我手动将 bootstrap js 添加到下一个 js 页面(
pages/gallery/[id].js
)的脚本中,如下所示:
import Script from "next/script";
import Layout from "../../layouts/interface";
import SlidingComponent from "../../components/slide";
export default function GalleryPage() {
const router = useRouter();
const {id} = router.query;
return (
<Layout>
<SlidingComponent />
<Script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" />
</Layout>
)
}
这最初是有效的,但是一旦第二张幻灯片图像进入,下一个js就会抛出以下错误:
Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'classList')
Call Stack
st._setActiveIndicatorElement
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:13913)
st._slide
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:15057)
st.next
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:10814)
st.nextWhenVisible
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:10883
我在网上找到了另一种方法来纠正错误。它说我应该像这样在我的
pages/_app.js
中导入 bootstrap js:
import 'bootstrap/dist/css/bootstrap.css'
import '../styles/globals.css'
import {useEffect} from "react";
//this is what the solution says:
useEffect(() => {
import("bootstrap/dist/js/bootstrap");
}, []);
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
但这也给了我以下错误:
https://nextjs.org/docs/messages/module-not-found
wait - compiling...
error - ./node_modules/bootstrap/dist/js/bootstrap.js:7:0
Module not found: Can't resolve '@popperjs/core'
Import trace for requested module:
./pages/_app.js
现在我什至不知道该怎么办,有人可以帮助我吗?
使用 npm、yarn 或 pnpm 安装 Bootstrap 和 React-Bootstrap。
npm i bootstrap react-bootstrap
转到
globals.css
目录中存在的 app
文件。在文件顶部添加以下代码:
@import "~bootstrap/dist/css/bootstrap.min.css";
您可以使用
className
向元素添加引导样式。
要使用
Container, Button, Form
等引导组件,您可以从react-bootstrap导入它们并像普通组件一样使用它们。
例如:
import { Button, Col, Container, Row } from "react-bootstrap";
export default function Home() {
return (
<Container>
<Row>
<Col>
<h1 className="text-danger fw-bold">Home</h1>
<Button variant="primary" className="mt-5 ">Click Me</Button>
</Col>
</Row>
</Container>
);
}
这样您就可以在 Next.js 应用程序中使用 bootstrap 了。