React 动态菜单-不限级递归菜单树

import {FC, useState} from "react";
import {Layout, Menu} from 'antd';
import {Link} from 'react-router-dom'
import {getData} from "../../mock-data";

const {Header, Content, Footer, Sider} = Layout;

//菜单数据结构
type  MenuData = {
    id: number,
    name: string;
    link: string;
    children: MenuData[];
};

const Home: FC = (props) => {
    const [openKeys, setOpenKeys] = useState([]);
    // setOpenKeys(props.openKeys)

    //定义方法:菜单无限级递归
    function tree(data: { id: string | number; name: string; link: string; children: any }[]) {
        return data.map((item) => {
            if (item.children === undefined) {
                return ({item.name})
            } else {
                return (
                    
                        {tree(item.children)}
                    
                )
            }
        })
    }

    //获取数据并绑定到类型上
    let menuData: MenuData[] = getData() as MenuData[];
    //动态菜单列表
    const elements = tree(menuData);

    return (
        
{ const keys1 = keys as string[]; setOpenKeys(keys1) }}>
{elements}
Header
{props.children}
Footer
); } export default Home;

你可能感兴趣的:(vue,react.js,javascript,前端)