簡體   English   中英

如何在 ReactJS 的 CoreUI 側邊欄菜單中有條件地呈現導航項

[英]How to make a nav item conditionally rendred in sidebar menu of CoreUI in ReactJS

TL;DR:如何在 CoreUI 的側邊欄菜單中有條件地呈現導航項?

所以我有這個來自CoreUI模板的導航菜單。 我創建了一個登錄導航項,點擊它會引導我到登錄頁面進行身份驗證。

  1. 當您通過身份驗證時: 菜單項將變為“注銷”,單擊它將引導您進入主頁

  2. 當您通過身份驗證時:菜單項將為“登錄”,單擊它將引導您進入登錄頁面

_nav.js:

const _nav = [
//...
  {
    component: CNavItem,
    name: 'Login',
    to: '/login',
    icon: <LoginIcon />,
  },
]

AppSidebar.js:

import navigation from '../_nav'
const AppSidebar = () => {
  return (
    <CSidebar
    >
      <CSidebarNav>
        <SimpleBar>
          <AppSidebarNav items={navigation} />
        </SimpleBar>
      </CSidebarNav>
      />
    </CSidebar>
  )

核心用戶界面 ReactJS

您可以將導航配置轉換為 function,它將用戶是否經過身份驗證作為參數並確定導航的登錄/注銷部分應該是什么:

const _nav = (isAuthenticated) => [
//...
  {
    component: CNavItem,
    name: isAuthenticated ? 'logout' : 'Login',
    to: isAuthenticated ? '/home' : '/login',
    icon: isAuthenticated ? <LogoutIcon /> : <LoginIcon />,
  },
]

只需在您的AppSidebar組件中將其稱為 function 並傳遞用戶的身份驗證狀態:

import navigation from '../_nav'
const AppSidebar = () => {
  const isAuthenticated = <the way you get your auth status>;

  return (
    <CSidebar
    >
      <CSidebarNav>
        <SimpleBar>
          <AppSidebarNav items={navigation(isAuthenticated)} />
        </SimpleBar>
      </CSidebarNav>
      />
    </CSidebar>
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM