您好,我写信询问更改与所选按钮关联的菜单的过程。我目前正在使用 Ant Design (antd) 和 React,并且想更新单击按钮时显示的选项。
能否指导一下如何在 Ant Design 框架内修改所选按钮的菜单内容?如果您能提供任何指示或帮助,我们将不胜感激。
感谢您对此事的关注。我期待您的回复。
真诚的
反应代码:
import BreadcumbCustom from 'views/share/BreadcumbCustom.jsx'
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { AppstoreOutlined, MailOutlined } from '@ant-design/icons'
import { Menu } from 'antd'
const items = [
{
label: 'Tracciati',
key: '1-1',
icon: <MailOutlined />,
},
{
label: 'Classificazioni',
key: '1-2',
icon: <AppstoreOutlined />,
},
]
export default function MenuConfigurazioni() {
const navigate = useNavigate()
const [current, setCurrent] = useState()
const handleDropdownItemClick = (e) => {
setCurrent(e.key)
if (e.key === '1-1') {
navigate('/admin/configurazione')
} else {
navigate('/admin/configurazione/classificazioni')
}
}
return (
<div>
<BreadcumbCustom title={'Configurazione'} />
<Menu
onClick={handleDropdownItemClick}
selectedKeys={[current]}
mode='horizontal'
items={items}
/>
</div>
)
}
你的实现是正确的,只有一点需要改进
let location = useLocation();
如果有人重新加载页面,这将处理 这是我的实现
import { App, Layout, Menu } from "antd";
import { Content, Header } from "antd/es/layout/layout";
import { useEffect, useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router";
import { AppLogo } from "../features/AppLogo";
import { AppFooter } from "../features/Footer";
export const DefaultLayout = () => {
const navigate = useNavigate();
let location = useLocation();
const [current, setCurrent] = useState(
location.pathname === "/" || location.pathname === ""
? "/"
: location.pathname
);
useEffect(() => {
if (location) {
if (current !== location.pathname) {
setCurrent(location.pathname);
}
}
}, [location]);
const handleClick = (key: string) => {
navigate(key);
};
return (
<App>
<Layout className="layout">
<Header style={{ display: "flex", alignItems: "center" }}>
<AppLogo />
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["/"]}
selectedKeys={[current]}
items={[
{
key: "/",
label: "Home",
onClick: (e) => {
handleClick(e.key);
},
},
{
key: "/login",
label: "Login",
onClick: (e) => {
handleClick(e.key);
},
},
{
key: "/register",
label: "Register",
onClick: (e) => {
handleClick(e.key);
},
},
]}
/>
</Header>
<Content style={{ padding: "0 50px", minHeight: "400px" }}>
<Outlet />
</Content>
</Layout>
<AppFooter />
</App>
);
};