PageLayout.tsx 2.68 KB
import React, { FC, useEffect, useState } from 'react';
import { Layout, Menu } from 'antd';
import {
  Link,
  Switch,
  withRouter,
  RouteComponentProps,
  Route,
  useLocation,
  useHistory,
} from 'react-router-dom';

import routes from '../router';
import './PageLayout.less';

const { Item } = Menu;
const { Header, Content, Sider } = Layout;

interface MenuItem {
  name: string
  key: string
  path: string
}

interface PageLayoutProp {}

const PageLayout:FC<PageLayoutProp & RouteComponentProps> = () => {
  const history = useHistory()
  const { pathname } = useLocation()
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])

  const onMenuClick = (menu: MenuItem) => {
    console.log(menu)
    if (menu.path === pathname) return
    const { key, path } = menu
    setSelectedKeys([key])
    history.replace(path)
  }

  useEffect(() => {
    const findKey = (path: string): any => routes.find(item => item.children ? findKey(path) : path === item.path)
    const filterRouteKey = findKey(pathname);
    if (filterRouteKey) {
      setSelectedKeys(filterRouteKey.key)
      history.replace(filterRouteKey.path)
    } else {
      setSelectedKeys(['SystemSetting'])
      history.replace('/system-setting')
    }
  }, [history, pathname])
  return (
    <Layout>
      <Header className="header">
        <div className="logo" />
      </Header>
      <Layout>
        <Sider width={200} className="site-layout-background">
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            style={{ height: '100%', borderRight: 0 }}
          >
            {routes.map(route => (
              <Item key={route.key} onClick={ () => onMenuClick(route) }>
                <Link to={route.path}>
                  <span>{route.name}</span>
                </Link>
              </Item>
            ))}
          </Menu>
        </Sider>
        <Layout style={{ padding: '24px 24px' }}>
          {/* <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>Home</Breadcrumb.Item>
            <Breadcrumb.Item>List</Breadcrumb.Item>
            <Breadcrumb.Item>App</Breadcrumb.Item>
          </Breadcrumb> */}
          <Content
            className="site-layout-background"
            style={{
              padding: 24,
              margin: 0,
              minHeight: 280,
            }}
          >
            <Switch>
              {routes.map(route => (
                <Route
                  key={route.key}
                  path={route.path}
                  component={route.component}
                />
              ))}
            </Switch>
          </Content>
        </Layout>
      </Layout>
    </Layout>
  )
}

export default withRouter(PageLayout);