zoukankan      html  css  js  c++  java
  • React+Ant Design 4.4.1实现左侧二级导航(可配置路由、所有路由层级可统一、可根据路由高亮菜单项、刷新时可自动展开定位到当前路由)

    package.json:

    {
      "name": "antd-demo",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@ant-design/icons": "^4.2.1",
        "@babel/core": "7.9.0",
        "@svgr/webpack": "4.3.3",
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.3.2",
        "@testing-library/user-event": "^7.1.2",
        "@typescript-eslint/eslint-plugin": "^2.10.0",
        "@typescript-eslint/parser": "^2.10.0",
        "antd": "^4.4.1",
        "axios": "^0.19.2",
        "babel-eslint": "10.1.0",
        "babel-jest": "^24.9.0",
        "babel-loader": "8.1.0",
        "babel-plugin-named-asset-import": "^0.3.6",
        "babel-preset-react-app": "^9.1.2",
        "bootstrap": "^3.3.7",
        "bootstrap-table": "^1.11.1",
        "bootstrapvalidator": "^0.5.4",
        "camelcase": "^5.3.1",
        "case-sensitive-paths-webpack-plugin": "2.3.0",
        "css-loader": "3.4.2",
        "dotenv": "8.2.0",
        "dotenv-expand": "5.1.0",
        "eslint": "^6.6.0",
        "eslint-config-react-app": "^5.2.1",
        "eslint-loader": "3.0.3",
        "eslint-plugin-flowtype": "4.6.0",
        "eslint-plugin-import": "2.20.1",
        "eslint-plugin-jsx-a11y": "6.2.3",
        "eslint-plugin-react": "7.19.0",
        "eslint-plugin-react-hooks": "^1.6.1",
        "file-loader": "4.3.0",
        "fs-extra": "^8.1.0",
        "html-webpack-plugin": "4.0.0-beta.11",
        "identity-obj-proxy": "3.0.0",
        "jest": "24.9.0",
        "jest-environment-jsdom-fourteen": "1.0.1",
        "jest-resolve": "24.9.0",
        "jest-watch-typeahead": "0.4.2",
        "jquery": "^3.3.1",
        "mini-css-extract-plugin": "0.9.0",
        "optimize-css-assets-webpack-plugin": "5.0.3",
        "pnp-webpack-plugin": "1.6.4",
        "postcss-flexbugs-fixes": "4.1.0",
        "postcss-loader": "3.0.0",
        "postcss-normalize": "8.0.1",
        "postcss-preset-env": "6.7.0",
        "postcss-safe-parser": "4.0.1",
        "react": "^16.13.1",
        "react-app-polyfill": "^1.0.6",
        "react-dev-utils": "^10.2.1",
        "react-dom": "^16.13.1",
        "react-router": "^4.2.0",
        "react-router-dom": "^4.2.0",
        "react-transition-group": "^4.4.1",
        "redux": "^4.0.5",
        "resolve": "1.15.0",
        "resolve-url-loader": "3.1.1",
        "sass-loader": "8.0.2",
        "semver": "6.3.0",
        "style-loader": "0.23.1",
        "terser-webpack-plugin": "2.3.5",
        "ts-pnp": "1.1.6",
        "url-loader": "2.3.0",
        "webpack": "4.42.0",
        "webpack-dev-server": "3.10.3",
        "webpack-manifest-plugin": "2.2.0",
        "workbox-webpack-plugin": "4.3.1",
        "ztree": "^3.5.24"
      },
      "scripts": {
        "start": "node scripts/start.js",
        "build": "node scripts/build.js",
        "test": "node scripts/test.js"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "proxy": "http://localhost:9999",
      "homepage": ".",
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      },
      "jest": {
        "roots": [
          "<rootDir>/src"
        ],
        "collectCoverageFrom": [
          "src/**/*.{js,jsx,ts,tsx}",
          "!src/**/*.d.ts"
        ],
        "setupFiles": [
          "react-app-polyfill/jsdom"
        ],
        "setupFilesAfterEnv": [
          "<rootDir>/src/setupTests.js"
        ],
        "testMatch": [
          "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
          "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
        ],
        "testEnvironment": "jest-environment-jsdom-fourteen",
        "transform": {
          "^.+\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
          "^.+\.css$": "<rootDir>/config/jest/cssTransform.js",
          "^(?!.*\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
        },
        "transformIgnorePatterns": [
          "[/\\]node_modules[/\\].+\.(js|jsx|ts|tsx)$",
          "^.+\.module\.(css|sass|scss)$"
        ],
        "modulePaths": [],
        "moduleNameMapper": {
          "^react-native$": "react-native-web",
          "^.+\.module\.(css|sass|scss)$": "identity-obj-proxy"
        },
        "moduleFileExtensions": [
          "web.js",
          "js",
          "web.ts",
          "ts",
          "web.tsx",
          "tsx",
          "json",
          "web.jsx",
          "jsx",
          "node"
        ],
        "watchPlugins": [
          "jest-watch-typeahead/filename",
          "jest-watch-typeahead/testname"
        ]
      },
      "babel": {
        "presets": [
          "react-app"
        ]
      }
    }
    

    src/route-config/index.js:

    import { SnippetsFilled, PieChartFilled, ApiFilled, PieChartOutlined } from '@ant-design/icons';
    
    const menuList = [
        {
            title: 'subnav 1', // 菜单标题名称
            key: '/admin', // 对应的path
            icon: SnippetsFilled // 图标名称
        },
        {
            title: 'subnav 2',
            key: '/products',
            icon: PieChartFilled,
            children: [ // 子菜单列表
                {
                    title: 'form',
                    key: '/form',
                    icon: 'bars'
                },
                {
                    title: 'menu',
                    key: '/menu',
                    icon: 'tool'
                },
            ]
        },
        {
            title: 'subnav 3',
            key: '/charts',
            icon: ApiFilled,
            children: [
                {
                    title: 'step',
                    key: '/step',
                    icon: 'bar-chart'
                },
                {
                    title: 'tabs',
                    key: '/tabs',
                    icon: 'line-chart'
                },
                {
                    title: 'table',
                    key: '/table',
                    icon: 'pie-chart'
                },
                {
                    title: 'message',
                    key: '/message',
                    icon: 'pie-chart'
                }
            ]
        },
        {
            title: 'subnav 4',
            key: '/notification',
            icon: PieChartOutlined,
            children: [
                {
                    title: 'progress',
                    key: '/progress',
                    icon: 'bar-chart'
                },
                {
                    title: 'spin',
                    key: '/spin',
                    icon: 'line-chart'
                },
                {
                    title: 'badge',
                    key: '/badge',
                    icon: 'pie-chart'
                },
                {
                    title: 'button',
                    key: '/button',
                    icon: 'pie-chart'
                },
                {
                    title: 'modal',
                    key: '/modal',
                    icon: 'pie-chart'
                }
            ]
        }
    ]
    
    export default menuList

    src/App.js:

    import React from 'react';
    import { notification } from 'antd'
    import { HashRouter, Route, Switch, Redirect } from 'react-router-dom'
    import Login from './Login';
    import First from './First';
    import './App.css';
    
    class App extends React.Component {
      constructor() {
        super();
        this.openNotificationWithIcon = type => {
          notification[type]({
            message: 'Notification Title',
            description:
              'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
          });
        }
      }
    
      clickHandle() {
        console.log("clicked!!!");
      }
    
      render() {
        return (<HashRouter>
          <Switch>
            <Route path="/login" component={Login} />
            <Route path="/" component={First} />
          </Switch>
        </HashRouter>)
      }
    }
    
    export default App;

    src/First.js:

    import React from 'react'
    import { Layout, Menu, Row, Col, Dropdown } from 'antd';
    import { DownOutlined } from '@ant-design/icons';
    import { Route, Link, Redirect, withRouter, Switch } from 'react-router-dom'
    import FormCom from './FormCom'
    import ButtonCom from './ButtonCom'
    import MenuCom from './MenuCom'
    import StepsCom from './StepsCom'
    import TabsCom from './TabsCom'
    import TableCom from './TableCom'
    import MessageCom from './MessageCom'
    import NotificationCom from './NotificationCom'
    import ProgressCom from './ProgressCom'
    import SpinCom from './SpinCom'
    import BadgeCom from './BadgeCom'
    import Admin from './Admin'
    import Modal from './Modal'
    import menuList from './route-config/index'
    
    const { SubMenu } = Menu;
    const { Header, Content, Sider } = Layout;
    
    class First extends React.Component {
        state = {
            rootSubmenuKeys: [], //只展开当前父级菜单
            openKeys: [], // 默认展开的菜单项
            collapsed: false
        };
    
        // 控制菜单左右收缩
        onCollapse = collapsed => {
            this.setState({ collapsed });
        };
    
        // 只展开当前父级菜单
        onOpenChange = openKeys => {
            const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
            if (this.state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
                this.setState({ openKeys });
            } else {
                this.setState({
                    openKeys: latestOpenKey ? [latestOpenKey] : [],
                });
            }
        };
    
        // 获取左侧菜单
        getMenuNodes = menuList => {
            const path = this.props.location.pathname
    
            return menuList.map(item => {
                if (!item.children) {
                    return (
                        <Menu.Item key={item.key} icon={<item.icon />}>
                            <Link to={item.key}>
                                <span>{item.title}</span>
                            </Link>
                        </Menu.Item>
                    )
                } else {
                    this.state.rootSubmenuKeys.push(item.key);
    
                    // 查找一个与当前请求路径匹配的子Item
                    const cItem = item.children.find(cItem => path.indexOf(cItem.key) === 0)
                    // 如果存在, 说明当前item的子列表需要打开
                    if (cItem) {
                        this.state.openKeys = [item.key];
                    }
    
                    return (
                        <SubMenu
                            key={item.key}
                            icon={<item.icon />}
                            title={item.title}
                        >
                            {this.getMenuNodes(item.children)}
                        </SubMenu>
                    )
                }
            })
        }
    
        componentWillMount() {
            this.menuNodes = this.getMenuNodes(menuList)
        }
    
        render() {
            if (Number(localStorage['token']) === 0) {
                // 自动跳转到登陆(在render()中)
                return <Redirect to='/login' />;
            }
    
            const loginOut = (e) => {
                e.preventDefault();
                localStorage['token'] = 0;
                this.props.history.replace("/login");
            }
    
            const menu = (
                <Menu>
                    <Menu.Item>
                        <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/" onClick={loginOut}>
                            退出
                        </a>
                    </Menu.Item>
                </Menu>
            );
    
            return (
                <Layout style={{ height: '100%' }}>
                    <Header className="header" style={{ position: 'fixed', zIndex: 1,  '100%', paddingLeft: '20px' }}>
                        <Row>
                            <Col span={10}><div className="logo" style={{ color: "#ffffff", fontSize: '32px', fontWeight: 'bold' }}>React App</div></Col>
                            <Col span={2} offset={12} style={{ textAlign: 'right' }}>
                                <Dropdown overlay={menu} trigger={['click']}>
                                    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                                        admin <DownOutlined />
                                    </a>
                                </Dropdown></Col>
                        </Row>
    
                    </Header>
                    <Layout style={{ height: '100%' }}>
                        {/*collapsible、collapsed、onCollapse:控制整个菜单的左右收缩*/}
                        <Sider width={200} style={{ background: '#000000' }} className="site-layout-background" collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}>
                            {/*selectedKeys:控制默认高亮菜单项,defaultOpenKeys、openKeys、onOpenChange:控制菜单展开*/}
                            <Menu
                                theme="dark"
                                mode="inline"
                                selectedKeys={this.props.location.pathname}
                                defaultOpenKeys={this.state.openKeys}
                                openKeys={this.state.openKeys}
                                onOpenChange={this.onOpenChange}
                                style={{ height: '100%', borderRight: 0, paddingTop: '60px' }}
                            >
                                {
                                    this.menuNodes
                                }
                            </Menu>
                        </Sider>
                        <Layout className="site-layout" style={{ paddingTop: 64 }}>
                            <Content
                                className="site-layout-background"
                                style={{
                                    padding: 15,
                                    margin: 0,
                                    height: '100%',
                                    overflow: 'auto'
                                }}
                            >
                                <Switch>
                                    <Redirect from='/' exact to='/admin' />
                                    <Route path="/admin" component={Admin}></Route>
                                    <Route path="/form" component={FormCom}></Route>
                                    <Route path="/menu" component={MenuCom}></Route>
                                    <Route path="/step" component={StepsCom}></Route>
                                    <Route path="/tabs" component={TabsCom}></Route>
                                    <Route path="/table" component={TableCom}></Route>
                                    <Route path="/message" component={MessageCom}></Route>
                                    <Route path="/notification" component={NotificationCom}></Route>
                                    <Route path="/progress" component={ProgressCom}></Route>
                                    <Route path="/spin" component={SpinCom}></Route>
                                    <Route path="/badge" component={BadgeCom}></Route>
                                    <Route path="/button" component={ButtonCom}></Route>
                                    <Route path="/modal" component={Modal}></Route>
                                    <Redirect to="/admin" />
                                </Switch>
                            </Content>
                        </Layout>
                    </Layout>
                </Layout>
            )
        }
    }
    
    export default withRouter(First)
  • 相关阅读:
    Android Service总结06 之AIDL
    Android Service总结05 之IntentService
    Android Service总结04 之被绑定的服务 -- Bound Service
    Android Service总结02 service介绍
    Android Service总结03 之被启动的服务 -- Started Service
    Android Service总结01 目录
    Android 数据存储04之Content Provider
    Android 数据存储03之SQLite
    Android 数据存储02之文件读写
    Android 数据存储01之SharedPreferences
  • 原文地址:https://www.cnblogs.com/samve/p/13537906.html
Copyright © 2011-2022 走看看