使用AntDesign的MenuItem如何再集成React Router

新版AntD已经不能使用MenuItem了,而是需要传入数据,这样使用React Router会有点麻烦。

解决方案是给Menu做一个click事件,里面再使用useNavigate分发路由,如下:

import { Breadcrumb, Layout, Menu } from 'antd';
import React, { Fragment } from 'react';
import {
  Routes,
  Route,
  useNavigate
} from "react-router-dom";

const { Header, Content, Footer } = Layout;

const items = [
  { label: '首页', key: 'item-', },
  { label: '帮助', key: 'item-help' },
]

const App: React.FC = () => {

  let navigate = useNavigate();

  return (
    <Layout className="layout" style={{ minHeight: '100vh' }}>
      <Header>
        <div className="logo" />
        <Menu
          theme="dark"
          mode="horizontal"
          defaultSelectedKeys={['item-my']}
          items={items}
          onClick={(e) => {
            navigate(e.key.replace("item-", ""))
          }}
        />
      </Header>
....
)
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *