Next.js -如何更改显示的组件?



我是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>

:如果有人点击"安全";在导航栏中,Security组件将被加载。

假设我已经建立了通知"Billing"one_answers";Security"组件。为了更新DOM,我看到了一个使用react-router-dom的指南。但我正试图坚持只使用Nextjs。

存储在"link"可以改变。但从"联系"来看在数据对象中,是否有更新组件的方法?如果有人能给我指出一个教程,例子,甚至是搜索什么,我将非常感激:)我今天晚上一直在研究,但还没有找到任何东西。

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

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

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

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

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

您可以通过修改当前对象的数据数组,并为每个链接添加对应的组件来实现这一点。

是这样的

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

创建一个将存储组件的状态(您可以将您的active状态修改为包含标签和对象的对象):

const [activeComponent, setActiveComponent] = useState(null);

然后,在onClick中更新它。

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

很好,然后你可以在需要的地方渲染活动组件:

<AppShell
<Navbar>
<Navbar.Section>
{links}
</Navbar.Section>
</Navbar>
>
{activeComponent}
</AppShell>

最新更新