当前位置:首页 > React

react typescript实现菜单

2026-01-26 21:08:18React

使用 React 和 TypeScript 实现菜单

定义菜单项类型

使用 TypeScript 定义菜单项的数据结构,确保类型安全。

interface MenuItem {
  id: string;
  label: string;
  path?: string;
  children?: MenuItem[];
}

创建菜单组件

构建一个可复用的菜单组件,支持嵌套子菜单。

react typescript实现菜单

import React, { useState } from 'react';

interface MenuProps {
  items: MenuItem[];
}

const Menu: React.FC<MenuProps> = ({ items }) => {
  const [activeSubMenu, setActiveSubMenu] = useState<string | null>(null);

  const handleClick = (id: string) => {
    setActiveSubMenu(activeSubMenu === id ? null : id);
  };

  return (
    <ul className="menu">
      {items.map((item) => (
        <li key={item.id} className="menu-item">
          <div 
            className="menu-label" 
            onClick={() => item.children && handleClick(item.id)}
          >
            {item.path ? <a href={item.path}>{item.label}</a> : item.label}
            {item.children && <span className="arrow">▼</span>}
          </div>
          {item.children && activeSubMenu === item.id && (
            <Menu items={item.children} />
          )}
        </li>
      ))}
    </ul>
  );
};

添加基本样式

为菜单添加简单的 CSS 样式,使其更美观。

.menu {
  list-style: none;
  padding: 0;
}

.menu-item {
  margin: 5px 0;
}

.menu-label {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: #f0f0f0;
  cursor: pointer;
}

.menu-label a {
  text-decoration: none;
  color: #333;
}

.arrow {
  margin-left: 10px;
}

使用菜单组件

在父组件中使用菜单组件,并传递菜单数据。

react typescript实现菜单

const App: React.FC = () => {
  const menuItems: MenuItem[] = [
    {
      id: '1',
      label: 'Home',
      path: '/home',
    },
    {
      id: '2',
      label: 'Products',
      children: [
        {
          id: '2-1',
          label: 'Laptops',
          path: '/products/laptops',
        },
        {
          id: '2-2',
          label: 'Phones',
          path: '/products/phones',
        },
      ],
    },
    {
      id: '3',
      label: 'Contact',
      path: '/contact',
    },
  ];

  return (
    <div className="app">
      <Menu items={menuItems} />
    </div>
  );
};

扩展功能

添加更多功能,如高亮当前选中菜单项或支持图标。

interface MenuItem {
  id: string;
  label: string;
  path?: string;
  icon?: React.ReactNode;
  children?: MenuItem[];
}

const Menu: React.FC<MenuProps> = ({ items }) => {
  const [activeSubMenu, setActiveSubMenu] = useState<string | null>(null);
  const [activeItem, setActiveItem] = useState<string | null>(null);

  const handleClick = (id: string) => {
    setActiveSubMenu(activeSubMenu === id ? null : id);
  };

  const handleSelect = (id: string) => {
    setActiveItem(id);
  };

  return (
    <ul className="menu">
      {items.map((item) => (
        <li 
          key={item.id} 
          className={`menu-item ${activeItem === item.id ? 'active' : ''}`}
        >
          <div 
            className="menu-label" 
            onClick={() => {
              if (item.children) {
                handleClick(item.id);
              } else {
                handleSelect(item.id);
              }
            }}
          >
            {item.icon && <span className="menu-icon">{item.icon}</span>}
            {item.path ? (
              <a href={item.path}>{item.label}</a>
            ) : (
              <span>{item.label}</span>
            )}
            {item.children && <span className="arrow">▼</span>}
          </div>
          {item.children && activeSubMenu === item.id && (
            <Menu items={item.children} />
          )}
        </li>
      ))}
    </ul>
  );
};

响应式设计

使用媒体查询使菜单在不同屏幕尺寸下表现良好。

@media (max-width: 768px) {
  .menu {
    width: 100%;
  }

  .menu-item {
    width: 100%;
  }
}

通过以上步骤,可以构建一个功能完善、类型安全的 React TypeScript 菜单组件。根据实际需求,可以进一步扩展功能或调整样式。

标签: 菜单react
分享给朋友:

相关文章

css制作二级菜单

css制作二级菜单

使用纯CSS制作二级菜单 通过CSS的:hover伪类和子选择器实现二级菜单的显示与隐藏。以下是一个典型的结构和样式示例: HTML结构 <nav class="menu"> &l…

react如何更新

react如何更新

更新 React 版本的方法 检查当前 React 版本 运行以下命令查看项目中安装的 React 版本: npm list react 更新 React 及相关依赖 通过 npm 或 yarn…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react 如何遍历

react 如何遍历

遍历数组 在React中遍历数组通常使用map方法,它会返回一个新的数组。map是处理数组并渲染列表元素的首选方法。 const items = ['Apple', 'Banana', 'Cherr…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…