{...}"입니다. 2. "handleSelectkeys(e){로 설정합니다. ...}" 선택된 상태; 3. "oli.push( {...}"입니다. 2. "handleSelectkeys(e){로 설정합니다. ...}" 선택된 상태; 3. "oli.push(

 >  기사  >  웹 프론트엔드  >  React에서 3단계 메뉴를 구현하는 방법

React에서 3단계 메뉴를 구현하는 방법

藏色散人
藏色散人원래의
2023-01-19 10:59:20836검색

React에서 3레벨 메뉴를 구현하는 방법: 1. 3레벨 상위 메뉴를 만들고 확장하는 방법은 "onOpenChange = (openKeys) => {...}"를 통해 2. "handleSelectkeys(e) ){... }" 선택한 상태를 설정합니다. 3. "oli.push(

React에서 3단계 메뉴를 구현하는 방법

이 튜토리얼의 운영 환경: Windows10 system, React18..0.0 버전, Dell G3 컴퓨터

상위 메뉴 표시줄(3단계 메뉴 표시줄)의 사이드바만 확장하기 위해

react + antd를 사용하여 3단계 메뉴를 구현하는 방법

페이지를 단순하게 유지하고 사용자 경험을 개선하기 위해 3단계 사이드바만 확장할 수 있는 요구 사항이 발생했습니다. 저도 오랫동안 온라인에서 검색했지만 완전히 충족되는 항목을 찾지 못했습니다.

3단계 상위 메뉴 확장 방법

onOpenChange = (openKeys) => {
        const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        let openList;
        if(this.state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            if(latestOpenKey&&latestOpenKey.length===3){
                openList = this.state.openKeys.filter((e)=>{
                    return e.length!==3;
                })
                this.setState({
                    openKeys:openList                });
            }else{
                this.setState({
                    openKeys:openKeys                });
            }           
        }else{
            if(latestOpenKey&&latestOpenKey.length===3){
                openList = this.state.openKeys.filter((e)=>{
                    return e.length!==3;
                })
                openList.push(latestOpenKey);
                this.setState({
                    openKeys:openList[1] ? openList : [openList[0],openList[2]]
                });
            }else{
                this.setState({
                    openKeys: latestOpenKey ? [latestOpenKey] : [],
                });
            }            
        }
    }</p>
<p><strong>선택 상태 설정</strong></p>
<pre class="brush:php;toolbar:false"> handleSelectkeys(e){
        if(this.state.isShow){
            this.setState({ 
                selectedKey:e.key,
                openKeys:e.keyPath[length] == 3  ? [e.keyPath[2],e.keyPath[1]] : [e.keyPath[0]],
                isShow:true
             }); 
        }       
    }

사이드바 컴포넌트 Menu.js 전체 코드

const data = this.props.list;
        var html = [];
        for(var i=0;i<data.length;i++){
            if(data[i].children){
                var li = []
                for(var j=0;j<data[i].children.length;j++){
                    var liData = data[i].children[j];
                    if(liData.children){
                        var oli = [];
                        for(var k=0;k<liData.children.length;k++){
                            oli.push(
                                <Menu.Item key={liData.children[k].url}>
                                    <Link to={
                                        {
                                            pathname:liData.children[k].url,
                                            state:{//三级菜单下传openKeys传两个值,展开两级
                                                parent:this.state.openKeys[0],
                                                child:this.state.openKeys[1]
                                            }
                                        }
                                    }>
                                        <span>{liData.children[k].text}</span>
                                    </Link>
                                </Menu.Item>
                            )
                        }
                        var oul = <SubMenu key={liData.id} title={<span>{liData.iconCls && <Icon type={liData.iconCls} />}<span>{liData.text}</span></span>}>{oli}</SubMenu>;
                        li.push(oul);
                    }else{
                        li.push(
                            <Menu.Item key={liData.url}>
                                <Link to={
                                    {
                                        pathname:liData.url,
                                        state:{//二级菜单下openKeys传一个值,展开一级
                                            parent:this.state.openKeys[0],
                                            // child:this.state.openKeys[1] ? this.state.openKeys[1] : &#39;&#39;
                                        }
                                    }
                                    
                                    } >
                                    {liData.iconCls && <Icon type={liData.iconCls} />}
                                    <span>{liData.text}</span>
                                </Link>
                            </Menu.Item>
                        );
                    }
                }
                var ul = <SubMenu key={data[i].id} title={<span>{data[i].iconCls && <Icon type={data[i].iconCls} />}<span>{data[i].text}</span></span>}>{li}</SubMenu>;
                html.push(ul);
            }else{
                html.push(
                    <Menu.Item key={data[i].url}>
                        <Link to={                           
                            {
                                pathname:data[i].url,
                                state:{//一级菜单下传空值,不展开菜单栏
                                    parent:&#39;&#39;
                                }
                            }
                            } >
                            {data[i].iconCls && <Icon type={data[i].iconCls} />}
                            <span>{data[i].text}</span>
                        </Link>
                    </Menu.Item>
                )
            }
        }

사이드바 데이터 menu.js

import React from 'react'import { Menu,Icon } from 'antd';import {Link,withRouter} from 'react-router-dom'const { SubMenu } = Menu;

 class Menus extends React.Component{
    constructor(props){
        super(props)
        this.state={
            openKeys:['1','100'],
            rootSubmenuKeys:[],
            selectedKeys:[this.props.history.location.pathname], //选中
            isShow:false //判断是否已经展开,如已展开停止重新赋值避免重新渲染和关系菜单         
        }
        this.handleSelectkeys = this.handleSelectkeys.bind(this)
    }
    UNSAFE_componentWillMount(){
        if(this.props.location.state){
            this.setState({
                openKeys:[this.props.location.state.parent,this.props.location.state.child ? this.props.location.state.child : '']
            })           
        }
          
      }
    componentDidMount(props,nextProps){
        var data = this.props.list;
        for(var i=0;i {
        const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        let openList;
        if(this.state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
            if(latestOpenKey&&latestOpenKey.length===3){
                openList = this.state.openKeys.filter((e)=>{
                    return e.length!==3;
                })
                this.setState({
                    openKeys:openList                });
            }else{
                this.setState({
                    openKeys:openKeys                });
            }           
        }else{
            if(latestOpenKey&&latestOpenKey.length===3){
                openList = this.state.openKeys.filter((e)=>{
                    return e.length!==3;
                })
                openList.push(latestOpenKey);
                this.setState({
                    openKeys:openList[1] ? openList : [openList[0],openList[2]]
                });
            }else{
                this.setState({
                    openKeys: latestOpenKey ? [latestOpenKey] : [],
                });
            }            
        }
    }
    render(){
        const data = this.props.list;
        var html = [];
        for(var i=0;i<data.length;i++){
            if(data[i].children){
                var li = []
                for(var j=0;j<data[i].children.length;j++){
                    var liData = data[i].children[j];
                    if(liData.children){
                        var oli = [];
                        for(var k=0;k<liData.children.length;k++){
                            oli.push(
                                <Menu.Item key={liData.children[k].url}>
                                    <Link to={
                                        {
                                            pathname:liData.children[k].url,
                                            state:{//三级菜单下传openKeys传两个值,展开两级
                                                parent:this.state.openKeys[0],
                                                child:this.state.openKeys[1]
                                            }
                                        }
                                    }>
                                        <span>{liData.children[k].text}</span>
                                    </Link>
                                </Menu.Item>
                            )
                        }
                        var oul = <SubMenu key={liData.id} title={<span>{liData.iconCls && <Icon type={liData.iconCls} />}<span>{liData.text}</span></span>}>{oli}</SubMenu>;
                        li.push(oul);
                    }else{
                        li.push(
                            <Menu.Item key={liData.url}>
                                <Link to={
                                    {
                                        pathname:liData.url,
                                        state:{//二级菜单下openKeys传一个值,展开一级
                                            parent:this.state.openKeys[0],
                                            // child:this.state.openKeys[1] ? this.state.openKeys[1] : &#39;&#39;
                                        }
                                    }
                                    
                                    } >
                                    {liData.iconCls && <Icon type={liData.iconCls} />}
                                    <span>{liData.text}</span>
                                </Link>
                            </Menu.Item>
                        );
                    }
                }
                var ul = <SubMenu key={data[i].id} title={<span>{data[i].iconCls && <Icon type={data[i].iconCls} />}<span>{data[i].text}</span></span>}>{li}</SubMenu>;
                html.push(ul);
            }else{
                html.push(
                    <Menu.Item key={data[i].url}>
                        <Link to={                           
                            {
                                pathname:data[i].url,
                                state:{//一级菜单下传空值,不展开菜单栏
                                    parent:&#39;&#39;
                                }
                            }
                            } >
                            {data[i].iconCls && <Icon type={data[i].iconCls} />}
                            <span>{data[i].text}</span>
                        </Link>
                    </Menu.Item>
                )
            }
        }
        return (
            
                {html}
            
        )
    }}export default withRouter(Menus);

추천 학습: "react 비디오 튜토리얼

"

위 내용은 React에서 3단계 메뉴를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.