Home > Web Front-end > Front-end Q&A > How to implement left menu in react

How to implement left menu in react

藏色散人
Release: 2022-12-20 14:41:16
Original
2843 people have browsed it

How to implement the left menu in react: 1. Define the routing structure, code such as "const Router = [{title: '',icon: 'laptop',...}]"; 2. Import router file, loop through map traversal; 3. Process the first-level menu and sub-level menu bar, code such as "renderSubMnenu = ({title,key,child}) => {...}".

How to implement left menu in react

#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.

How to implement the left menu in react?

Use React to implement the left menu bar

Introduction: Use React to implement the left menu bar

antd is specially customized for react The background component library provides a large number of components for developers to use.

  • Official website addressClick to jump

  • in In the middle and backend, menu items are essential. Today, we will use react combined with antd to configure a menu column

First define the routing structure

const Router = [{
        title: '控制台',
        icon: 'laptop',
        key: '/index',
        role: ["user", "information", "product"]
    },
    {
        title: '用户管理',
        icon: 'laptop',
        key: '/index/user', // 菜单
        role: ["information", "user"], // 角色 
        child: [{
                key: '/index/user/list',
                title: '用户列表',
                icon: '',
                role: ["user"]
            },
            {
                key: '/index/user/add',
                title: '添加用户',
                icon: '',
                role: ["user"]
            }
        ]
    },
    {
        title: '部门管理',
        icon: 'bars',
        key: '/index/department',
        role: ["user"],
        child: [{
                key: '/index/department/list',
                title: '部门列表',
                icon: '',
                role: ["user"]
            },
            {
                key: '/index/department/add',
                title: '添加部门',
                icon: '',
                role: ["user"]
            },
        ]
    },
    {
        title: '加班',
        icon: 'info-circle-o',
        key: '/home/abouta'
    }
]
export default Router;
Copy after login

Use the one provided by antd Menu

  • This needs to be considered in some situations. When the route has a first-level menu or the submenu below needs to be processed

  • Introduce the router file and traverse it through map Loop

  • Traverse through the map to determine whether there is a second-level menu

-

import Router from './../../router/index'
import {  Menu } from 'antd';
const { SubMenu } = Menu;
<Menu
                    onOpenChange={this.openMenu}
                    onClick={this.selectMenu}
                    theme="dark"
                    mode="inline"
                    selectedKeys={selectedKeys}
                    openKeys={openKeys}
                    style={{ height: &#39;100%&#39;, borderRight: 0 }}
                    >
                    {
                        Router && Router.map(firstItem => {
                            return firstItem.child && firstItem.child.length > 0 ? this.renderSubMnenu(firstItem) : this.renderMenu(firstItem)
                        }) 
                    }
                    
                    </Menu>
Copy after login

Processing the first-level menu

    renderMenu =({title,key}) => {
        return (
            <Menu.Item key={key}>
                <Link to={key}>
                    <span>{title}</span>
                </Link>
            </Menu.Item>
        )
    }
Copy after login

Processing sub-menu bar recursion

  renderSubMnenu = ({title,key,child}) => {
        return (
            <SubMenu key={key} title={title}>
                {
                    child && child.map(item => {
                        return item.child && item.child.length > 0 ? this.renderSubMnenu(item) : this.renderMenu(item)
                    })
                }
            </SubMenu>
        )
        
    }
Copy after login

Processing menu selection, highlighting, refreshing and keeping the selected state

  • Operation based on the api provided by antd

  • selectedKeys The currently selected menu item key array openKeys, the currently expanded SubMenu menu item key array

constructor(props) {
        super(props);
        this.state= {
            selectedKeys:[],
            openKeys:[]
        }
    }
    componentDidMount(){
        // 菜单状态
        const pathname = this.props.location.pathname;
        const menukey = pathname.split("/").slice(0,3).join(&#39;/&#39;);
        const menuHigh = {
            selectedKeys: pathname,
            openKeys: menukey
        }
        this.selectMenuHigh(menuHigh)
    }
    selectMenu =({item,key,keyPath}) => {
        // 选中菜单
        const menuHigh = {
            selectedKeys: key,
            openKeys: keyPath[keyPath.length - 1]
        }
        this.selectMenuHigh(menuHigh)
    }
    openMenu = (openKeys) => {
        // 展开
        this.setState({
            openKeys: [openKeys[openKeys.length - 1]]
        })
    }
    selectMenuHigh = ({selectedKeys,openKeys}) => {
        // 菜单高亮
        this.setState({
            selectedKeys: [selectedKeys],
            openKeys: [openKeys]
        })
    }
Copy after login

Complete code

import React, { Component,Fragment } from 'react'
import {Link,withRouter} from 'react-router-dom'
import Router from './../../router/index'
import {  Menu } from 'antd';
const { SubMenu } = Menu;
class AsideMenu extends Component {
    constructor(props) {
        super(props);
        this.state= {
            selectedKeys:[],
            openKeys:[]
        }
    }
    componentDidMount(){
        // 菜单状态
        const pathname = this.props.location.pathname;
        const menukey = pathname.split("/").slice(0,3).join(&#39;/&#39;);
        const menuHigh = {
            selectedKeys: pathname,
            openKeys: menukey
        }
        this.selectMenuHigh(menuHigh)
    }
    selectMenu =({item,key,keyPath}) => {
        // 选中菜单
        const menuHigh = {
            selectedKeys: key,
            openKeys: keyPath[keyPath.length - 1]
        }
        this.selectMenuHigh(menuHigh)
    }
    openMenu = (openKeys) => {
        // 展开
        this.setState({
            openKeys: [openKeys[openKeys.length - 1]]
        })
    }
    selectMenuHigh = ({selectedKeys,openKeys}) => {
        // 菜单高亮
        this.setState({
            selectedKeys: [selectedKeys],
            openKeys: [openKeys]
        })
    }
    // 处理一级菜单栏
    renderMenu =({title,key}) => {
        return (
            <Menu.Item key={key}>
                <Link to={key}>
                    <span>{title}</span>
                </Link>
            </Menu.Item>
        )
    }   
    // 处理子级菜单栏
    renderSubMnenu = ({title,key,child}) => {
        return (
            <SubMenu key={key} title={title}>
                {
                    child && child.map(item => {
                        return item.child && item.child.length > 0 ? this.renderSubMnenu(item) : this.renderMenu(item)
                    })
                }
            </SubMenu>
        )
        
    }
    render() {
        const { selectedKeys,openKeys } = this.state
        return (
            
                
                    {
                        Router && Router.map(firstItem => {
                            return firstItem.child && firstItem.child.length > 0 ? this.renderSubMnenu(firstItem) : this.renderMenu(firstItem)
                        }) 
                    }
                    
                    
            
        )
    }
}
export default withRouter(AsideMenu)
Copy after login

Recommended Study: "react video tutorial"

The above is the detailed content of How to implement left menu in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template