【发布时间】: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/link的Link