当前位置:首页 > 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
分享给朋友:

相关文章

vue实现导航菜单

vue实现导航菜单

Vue 实现导航菜单的方法 基础路由导航实现 在 Vue 项目中,使用 vue-router 可以轻松实现导航菜单功能。首先安装并配置路由: npm install vue-router 在 ro…

如何制作css导航菜单

如何制作css导航菜单

创建基本HTML结构 导航菜单的基础是HTML结构。使用<nav>标签包裹无序列表<ul>,每个菜单项用<li>标签表示,链接用<a>标签。 <…

如何评价react native

如何评价react native

React Native 的优势 跨平台开发效率高:基于 JavaScript 和 React 语法,可同时开发 iOS 和 Android 应用,减少重复代码量。性能接近原生:通过原生组件渲染,性能…

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

react如何取消渲染

react如何取消渲染

取消渲染的方法 在React中,取消渲染通常指的是在某些条件下阻止组件渲染或中断正在进行的渲染过程。以下是几种常见的方法: 条件渲染 通过条件判断决定是否渲染组件或部分内容。可以使用if语句或三元…

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gr…