简体   繁体   English

NextJs 布局登录页面?

[英]NextJs Layout Login page?

I'm covering app js with layout.我正在用布局覆盖应用程序 js。 I have the sidebar on the left and my pages on the right.我的侧边栏在左边,我的页面在右边。 But what I want is that the sidebar should not appear on the login page, how can I edit it?但是我想要的是侧边栏不应该出现在登录页面上,我该如何编辑它?

_app.js _app.js 在此处输入图像描述

Layout.js布局.js 在此处输入图像描述

you can add a condition with pathname to showing the component or not您可以添加带有pathname的条件以显示组件或不显示组件

something like this:像这样的东西:

const router = useRouter():

return (
   ...
   {router.pathname !== '/login' && <Sidebar path={router.route} />}
   ...
)

If you have some pages that are protected and can be seen by logged in user than you would need Public and Protected Routes and you can show in your Public routes only如果您有一些受保护的页面并且可以被登录用户看到,那么您将需要公共和受保护的路由,并且您只能在公共路由中显示

If this is not the case then solution mentioned by @kaveh karami is good如果不是这种情况,那么@kaveh karami 提到的解决方案很好

I'm thinking you should use Option 4 of the Persistent Layout Patterns article by Adam Wathan (the getLayout Pattern) to implement the layout and pass a prop to conditionally render the sidebar.我认为您应该使用Adam Wathan 撰写的 Persistent Layout Patterns 文章的选项 4( getLayout模式)来实现布局并传递一个道具以有条件地呈现侧边栏。

In this way, your Login / Register page controls the layout rendering这样,您的登录/注册页面控制布局呈现

// Layout.js
export default function Layout({ showSidebar, children, ...rest }){
  return (
    ...
    {showSidebar && <Sidebar />}
    ...
  )
}

export function getLayout(page, props) {
    return <Layout {...props}>{page}</DefaultLayout>
}


// Login.js
import { getLayout as getDefaultLayout } from './Layout.js'

function Login(){
  return (
    ...
  )
}

Login.getLayout = page => getDefaultLayout(page, { showSidebar: true})

I would create a HOC(Higher-Order-Component) called WithSidebar:我将创建一个名为 WithSidebar 的 HOC(高阶组件):

import Main from '../../components/Main/Main';
import Sidebar from '../../components/Sidebar/Sidebar';
import classes from './WithSidebar.module.scss';

const WithSidebar = (Component) => {

    return props => (
        <div className={classes.WithSidebar}>
            <Sidebar />
            <Main className={classes.Container}>
                <Component {...props} />
            </Main>
        </div>
    );
};

export default WithSidebar;

And then export the pages that should include the sidebar like so:然后像这样导出应该包含侧边栏的页面:


import WithSidebar from '../hoc/WithSidebar/WithSidebar';

const MyPage = () => {

    return (...)
}

export default WithSidebar(MyPage)

I find this approach really cleaner than conditionally rendering based on the pathname.我发现这种方法比基于路径名的条件渲染更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM