【问题标题】:Next.js - how to change the component that is displayed?Next.js - 如何更改显示的组件?
【发布时间】:2023-01-12 17:04:59
【问题描述】:

我是 React/Nextjs 的新手。

我用这个作为模板: https://ui.mantine.dev/component/navbar-simple

这是示例数据:

const data = [
  { link: '/notifications', label: 'Notifications', icon: IconBellRinging },
  { link: '/billing', label: 'Billing', icon: IconReceipt2 },
  { link: '/security', label: 'Security', icon: IconFingerprint },

它用于构建导航栏:

export function NavbarSimple() {
  const { classes, cx } = useStyles();
  const [active, setActive] = useState('Billing');

  const links = data.map((item) => (
    <a
      className={cx(classes.link, { [classes.linkActive]: item.label === active })}
      href={item.link}
      key={item.label}
      onClick={(event) => {
        event.preventDefault();
        setActive(item.label);
      }}
    >
      <item.icon className={classes.linkIcon} stroke={1.5} />
      <span>{item.label}</span>
    </a>
  ));

  return (
    <AppShell
      <Navbar>
         <Navbar.Section>
           {links}
         </Navbar.Section>
      </Navbar>
   >
   {/* 
      I am trying to get the components to be swapped/updated here
   */}
   </AppShell>

目标:如果有人在导航栏中单击“安全”,将加载安全组件。

假设我已经构建了“通知”、“计费”和“安全”组件。 要更新 DOM,我看到了使用 react-router-dom 来执行此操作的指南。但我试图坚持只使用 Nextjs。

可以更改存储在“链接”中的任何字符串。但是从数据对象中的“链接”,有没有办法更新组件呢? 如果有人可以向我指出教程、示例,甚至是要搜索的内容,我将不胜感激 :) 我今晚一直在研究,但还没有找到任何东西。

我也做了一个codesandbox:https://wytec9.csb.app/

【问题讨论】:

  • 如果您使用的是 Nextjs,则不需要 react-router-dom。您不需要创建路由并处理组件中的更改。在这里查看如何在 Nextjs 中创建页面:nextjs.org/docs/basic-features/pages。你应该使用来自 next/linkLink

标签: reactjs next.js


【解决方案1】:

你可以在这个组件中有一个函数,它会根据值带来你想要的组件,一个简单的例子:

const renderComponent = () => {
  if(active === 'Billing'){
    return <Billing/>
  } else if (){
    // you get the idea
  }
}

现在调用该函数来调出正确的组件:

  return (
    <AppShell
      <Navbar>
         <Navbar.Section>
           {links}
         </Navbar.Section>
      </Navbar>
   >
   {renderComponent()}
   </AppShell>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    相关资源
    最近更新 更多