Shr*_*hav 32 javascript reactjs server-side-rendering next.js
如何不使用布局组件包装特定页面_app.js?
例如,我有两个页面 aspages/home和pages/about,现在我怎么能不用组件包装我的pages/home页面Layout呢?
页面/_app.js
import "../styles/globals.css";
import Layout from "../components/Layout";
function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
Run Code Online (Sandbox Code Playgroud)
我尝试过的:
页面/_app.js
function MyApp({ Component, pageProps }) {
console.log(typeof Component); // gives me a function
switch (Component) {
case Home():
return <Component {...pageProps} />;
default:
return (
<Layout>
<Component {...pageProps} />{" "}
</Layout>
);
}
}
Run Code Online (Sandbox Code Playgroud)
页面/home.js
import React from 'react';
const Home= () => {
return (<div>Hello</div>);
};
export default Home;
Run Code Online (Sandbox Code Playgroud)
Shr*_*hav 41
通过检查 appProps.router.pathname传递给它的属性。
function MyApp({ Component, pageProps, ...appProps }: AppProps) {
// make function that will return the children based on router.pathname
const getContent = () => {
// array of all the paths that doesn't need layout
if ([`/dashboard`].includes(appProps.router.pathname))
return <Component {...pageProps} />;
return (
<Layout>
<Component {...pageProps} />{" "}
</Layout>
);
};
return <ApplicationWrapper>{getContent()}</ApplicationWrapper>;
}
Run Code Online (Sandbox Code Playgroud)
function MyApp({ Component, pageProps, ...appProps }: AppProps) {
// use a LayoutComponent variable
// that switches to actual Layout or React.Fragment (no layout)
// accordingly to pathname
const isLayoutNeeded = [`/dashboard`].includes(appProps.router.pathname);
const LayoutComponent = isLayoutNeeded ? Layout : React.Fragment;
return (
<ApplicationWrapper>
<LayoutComponent>
<Component />
</LayoutCompnent>
</ApplicationWrapper>
);
}
Run Code Online (Sandbox Code Playgroud)
提示:
您可以用来path.startsWith检查所有路径,例如
if(router.pathname.startsWith(`/dashboard`))
Run Code Online (Sandbox Code Playgroud)
小智 30
我认为使用每页布局有更干净的方法。我目前正在通过为所有页面创建默认布局并为需要特定布局的页面(例如在我的登录和注册页面中)覆盖它来完成此简单操作。
export default function LoginPage() {
return {
/** Some JSX */
}
}
// Return the page without additional layout.
LoginPage.getLayout = (page) => page
export default function MyApp({ Component, pageProps }) {
// Use the specified page layout or fallback to the default one.
const getLayout = Component.getLayout ?? defaultPageLayout
return getLayout(<Component {...pageProps} />)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33404 次 |
| 最近记录: |