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/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/Login.js:

import React from 'react'
import { Button, notification } from 'antd';
import $ from 'jquery'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.min.js'
import 'bootstrap-table/dist/bootstrap-table.css'
import 'bootstrap-table/dist/bootstrap-table.min.js'
import 'bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js'
import 'ztree/css/metroStyle/metroStyle.css'
import 'bootstrapvalidator/dist/css/bootstrapValidator.min.css'
import 'bootstrapvalidator/dist/js/bootstrapValidator.min.js'
import HTTP from './Http.js'

const openNotificationWithIcon = (type, message, description) => {
    notification[type]({
      message,
      description
    });
};

export default class Login extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (<div id="login-container" className="wallBg">
            <div id="login">
                <form id="login-form" className="form-horizontal">
                    <div id="login-name">
                        <div id="login-logo">React App</div>
                    </div>

                    
                    <div className="form-group login-input-container" id="login-user-name-container">
                        <span className="input-group-addon login-icon" style={{ color: '#555555' }}>
                            <i className="glyphicon glyphicon-user" aria-hidden="true" style={{ paddingTop: '2px' }}></i>
                        </span>
                        <div className="col-lg-12 col-md-12 col-sm-12" style={{ height: '34px' }}>
                            <input type="text" style={{width: 0}}/>
                            <input
                                type="text"
                                className="form-control login-input"
                                id="login-user-name"
                                name="loginUserName"
                                placeholder="用户名"
                            />
                            <input type="text" style={{width: 0}}/>
                            <div className="login-input-below bg-white" id="login-user-name-tips"></div>
                        </div>
                    </div>

                    <div className="form-group login-input-container" id="login-password-container">
                        <span className="input-group-addon login-icon" style={{ color: '#555555' }}>
                            <i className="glyphicon glyphicon-lock" aria-hidden="true" style={{ paddingTop: '2px' }}></i>
                        </span>

                        <div className="col-lg-12 col-md-12 col-sm-12" style={{ height: '34px' }}>
                            <input type="password" style={{width: 0}}/>
                            <input
                                type="password"
                                className="form-control login-input"
                                id="login-password"
                                name="loginPassword"
                                placeholder="密码"
                            />
                            <div className="login-input-below bg-white" id="login-password-tips"></div>
                        </div>
                    </div>

                    <button
                        className="btn btn-success"
                        id="login-submit"
                        type="submit"
                    >登&nbsp;&nbsp;&nbsp;&nbsp;录</button>

                    <div id="copyright"></div>
                </form>
            </div>
        </div>)
    }

    componentDidMount() {
        let _this = this;

        $("#login-form")
        .bootstrapValidator({
            message: "This value is not valid",
            feedbackIcons: {
                valid: "glyphicon glyphicon-ok",
                invalid: "glyphicon glyphicon-remove",
                validating: "glyphicon glyphicon-refresh"
            },
            fields: {
                loginUserName: {
                    message: "用户名无效",
                    validators: {
                        notEmpty: {
                            message: "用户名不能为空"
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_()()\u4e00-\u9fa5]{1,32}$/,
                            message:
                                "用户名为1至32位汉字、字母、数字、下划线或中英文括号,为了能在路径中尽可能多的显示文件夹,请尽量减小名称长度!"
                        }
                    }
                },
                loginPassword: {
                    message: "密码无效",
                    validators: {
                        notEmpty: {
                            message: "密码不能为空"
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_()()\u4e00-\u9fa5]{1,32}$/,
                            message:
                                "密码为1至32位汉字、字母、数字、下划线或中英文括号,为了能在路径中尽可能多的显示文件夹,请尽量减小名称长度!"
                        }
                    }
                }
            }
        })
        .on("success.form.bv", function (e) {
            e.preventDefault();

            let param = new URLSearchParams()
            param.append('username', $("#login-user-name").val())
            param.append('password', $("#login-password").val())

            HTTP({
                method: "POST",
                url: "/article/check_login_status/",
                data: param
            })
                .then(res => {
                    if (res.ret) {
                        localStorage['token'] = 20;
                        //this.props.history.push("/first/admin")
                        $("#login-form")[0].reset();
                        $("#login-form").data('bootstrapValidator').resetForm();
                        _this.props.history.replace("/");
                    } else {
                        notification['error']({
                            message: '错误提示',
                            description: '用户名或秘密错误,登录失败!'
                        });
                    }
                })
                .catch(err => {
                    notification['error']({
                        message: '错误提示',
                        description: '网络错误,登录失败!'
                    });
                });
        });
    }
}

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, width: '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)

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
posted @ 2020-08-20 21:22  Samve  阅读(251)  评论(0编辑  收藏  举报