我想将我的自定义类添加到某些页面。例如
所有页面都必须是此类fixed-header
例外,此路由:
/cart/step-1
/login
此类添加或删除 body 元素。
<body className="bg-gray fixed-header"
但我不知道如何处理这种情况?
在您的页面目录中创建自定义_document.js
和_app.js
。
一个用于检查主体上是否存在类的小工具(为了避免重复类,感谢@juliomalves 的建议):
// ./utils/hasClasses
const hasClasses = () =>
document.body.classList.contains("bg-gray") &&
document.body.classList.contains("fixed-header");
export default hasClasses;
在 中_document.js
,使用__NEXT_DATA__
prop 访问当前页面,检查页面是否在您允许的路径中,并将类添加到 body。
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
// Add more routes here if you want to use the same classes
allowedRoutes = ["/login", "/cart/step-1"];
getColor() {
const { page } = this.props?.__NEXT_DATA__;
if (this.allowedRoutes.includes(page))
return "bg-gray fixed-header";
return "";
}
render() {
return (
<Html>
<Head />
<body className={this.getColor()}>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
上面的代码总是在服务器上运行。类不会附加到客户端导航的正文中。
要解决上述问题,请_app.js
在 a 中使用相同的逻辑useEffect
,以便在客户端渲染时添加正确的类。
import { useEffect } from "react";
import { useRouter } from "next/router";
import "../styles.css";
import hasClasses from "./utils/hasClasses";
function MyApp({ Component, pageProps }) {
const { pathname: page } = useRouter();
const allowedRoutes = ["/login", "/cart/step-1"];
useEffect(() => {
if (!hasClasses() && allowedRoutes.includes(page))
document.body.className += "bg-gray fixed-header";
else if (hasClasses()) {
// Don't want the styles in other pages, remove if exists.
// Up to your implementation on how you want to handle this.
document.body.classList.remove("bg-gray");
document.body.classList.remove("fixed-header");
}
});
return <Component {...pageProps} />;
}
export default MyApp;
这解决了客户端导航在允许的路线上正确应用类的问题。中的代码_document.js
确保在服务器呈现页面时,将其发送到下游并应用正确的类,以便不会在客户端上导致不正确的样式闪烁。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句