react关于手搓antd pro面包屑的经验(写的不好请见谅)

news/2025/2/6 9:35:04 标签: react.js, 前端, javascript

我们先上代码,代码里面都有注释,我是单独写了一个组件,方便使用,在其他页面引入就行了

还使用了官方的Breadcrumb组件

import React, { useEffect, useState } from 'react';
import { Breadcrumb, Button } from 'antd';
import { useLocation, NavLink, useNavigate } from 'react-router-dom';

// 定义面包屑项的类型
interface LocaItem {
  path: string;
  title: string;
}

interface CustomBreadcrumbProps {
  title: string; // 当前页面的标题,动态传递
}

const CustomBreadcrumb: React.FC<CustomBreadcrumbProps> = ({ title }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loca, setLoca] = useState<LocaItem[]>([]);

  useEffect(() => {
    // 获取存储的面包屑数据
    const storedLoca = JSON.parse(sessionStorage.getItem('loca') || '[]');

    // 创建新面包屑项
    const newObject: LocaItem = {
      path: location.pathname,
      title: title, // 使用传入的 title 作为当前页面的标题
    };

    // 判断 loca 中是否有相同的 title
    const isExist = storedLoca.some((item: LocaItem) => item.title === newObject.title);

    // 如果不存在相同的 title,就 push 新对象
    if (!isExist) {
      storedLoca.push(newObject);
      sessionStorage.setItem('loca', JSON.stringify(storedLoca)); // 存储新的面包屑数据
    }

    setLoca(storedLoca); // 更新组件状态
  }, [location.pathname, title]); // 每次路径或标题变化时,更新面包屑

  // 删除面包屑项
  const handleRemove = (path: string) => {
    console.log(location.pathname);
    console.log(path);
    // 检查路径是否相同
    if (location.pathname === path) {
      const pathlink = JSON.parse(sessionStorage.getItem('loca') || '[]');
      const pathlinkLength = pathlink.length - 1;

      if (path === pathlink[pathlinkLength].path) {
        const newPath = String(pathlink[pathlinkLength - 1]?.path);

        // 延迟跳转,确保状态更新后执行
        setTimeout(() => {
          navigate(newPath || '/'); // 如果路径为空,跳转到默认页面
        }, 0);
      } else {
        const newPath = String(pathlink[pathlinkLength - 2]?.path);

        // 延迟跳转,确保状态更新后执行
        setTimeout(() => {
          navigate(newPath || '/'); // 如果路径为空,跳转到默认页面
        }, 0);
      }
    }

    // 更新面包屑数据
    const updatedLoca = loca.filter((item) => item.path !== path);
    sessionStorage.setItem('loca', JSON.stringify(updatedLoca)); // 更新 sessionStorage
    setLoca(updatedLoca); // 更新状态
  };

  // 渲染面包屑项
  const breadcrumbItems = loca.map((item: LocaItem) => ({
    title: (
      <span style={
  
  { display: 'flex', alignItems: 'center', marginLeft: '10px' }}>
        <NavLink
          to={item.path}
          style={({ isActive }) => ({
            fontWeight: isActive ? 'bold' : 'normal', // 高亮显示
            color: isActive ? '#1890FF' : 'normal', // 当前项文字颜色
            backgroundColor: isActive ? '#e6f7ff' : 'normal', // 当前项背景颜色
            borderBottom: isActive ? '1px solid #1890FF' : 'normal',
            borderRadius: '0',
            height: '30px',
            lineHeight: '30px',
            padding: '0 10px 0 10px',
          })}
        >
          {item.title}
        </NavLink>
        {/* 关闭按钮 */}
        <Button
          onClick={() => handleRemove(item.path)} // 点击删除当前面包屑项
          disabled={item.title === "首页"} // 禁用“首页”按钮
          type="link"
          icon={<span style={
  
  { fontSize: '16px' }}>×</span>}
          style={
  
  {
            padding: 0,
            fontSize: '16px',
            display: item.title === "首页" ? 'none' : 'block',
            width: '20px',
            margin: item.title === "首页" ? '0 5px 0 0' : '0',
          }}
        />
      </span>
    ),
  }));

  return (
    <Breadcrumb
      style={
  
  {
        margin: '16px 0',
        height: '30px',
      }}
      items={breadcrumbItems} // 使用动态生成的面包屑项
      separator="" // 去掉默认的斜杠分隔符
      itemRender={(route) => {
        return (
          <span style={
  
  { marginRight: '10px',whiteSpace:'nowrap' }}>{route.title}</span> // 给每个面包屑项加间距
        );
      }}
    />
  );
};

export default CustomBreadcrumb;

然后在其他页面引入

javascript">import Breadcrumbs from '../../../src/components/Breadcrumb/Breadcrumb';

使用:

title是面包屑的名称,你也可以获取当前路由的title,写个动态的

<Breadcrumbs title="需求管理" />

效果:


http://www.niftyadmin.cn/n/5842830.html

相关文章

双亲委派(jvm)

1.双亲委派 在 Java 中&#xff0c;双薪委派通常是指双亲委派模型&#xff0c;它是 Java 类加载器的一种工作模式&#xff0c;用于确保类加载的安全性和一致性。以下是其相关介绍&#xff1a; 定义与作用 定义&#xff1a;双亲委派模型要求除了顶层的启动类加载器外&#xf…

SAP HCM 读取特定0014信息类型(特定月份)数据

导读 0014信息类型:0014是HCM的周期性维护数据&#xff0c;也就是说默认我维护的周期时间很长&#xff0c;在一段时间内不需要维护&#xff0c;减少维护的工作量&#xff0c;今天遇到一个朋友问的问题&#xff0c;0014信息类型能读取特定月份的数据&#xff0c;例如我需要维护…

ES6 变量解构赋值总结

1. 数组的解构赋值 1.1 基本用法 // 基本数组解构 const [a, b, c] [1, 2, 3]; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3// 跳过某些值 const [x, , y] [1, 2, 3]; console.log(x); // 1 console.log(y); // 3// 解构剩余元素 const [first, ...re…

在本地快速部署deepseek

第一步&#xff0c;找到网站&#xff0c;下载&#xff1a; 首先找到Ollama &#xff0c; 根据自己的电脑下载对应的版本 。 我个人用的是Windows 我就先尝试用Windows版本了 &#xff0c;文件不是很大&#xff0c;下载也比较的快 第二部就是安装了 &#xff1a; 安装完成后提示…

12.外观模式(Facade Pattern)

定义 外观模式&#xff08;Facade Pattern&#xff09; 是一种结构型设计模式&#xff0c;它通过为复杂的子系统提供一个统一的接口&#xff0c;使得子系统的使用更加简化。外观模式通常隐藏了复杂的内部子系统&#xff0c;使得客户端可以通过一个简单的接口与这些子系统进行交…

11.享元模式 (Flyweight)

定义 Flyweight 模式&#xff08;享元模式&#xff09; 是一种结构型设计模式&#xff0c;它旨在通过共享对象来有效支持大量细粒度对象的复用。该模式主要通过共享细节来减少内存使用&#xff0c;提升性能&#xff0c;尤其在需要大量对象时非常有效。 基本思想&#xff1a; …

Security(四)授权模块详解:注解授权

Security&#xff08;四&#xff09;授权模块详解&#xff1a;注解授权 前言 &#xff1a;项目中常用的授权方式就是注解授权&#xff0c;这里之讲解注解授权。 文章目录 Security&#xff08;四&#xff09;授权模块详解&#xff1a;注解授权前言 &#xff1a;项目中常用的授…

【PromptCoder + Bolt.new】Cascade模式自动生成页面和对应的路由

【PromptCoder Bolt.new】Cascade模式自动生成页面和对应的路由 官网&#xff1a;PromptCoder PromptCoder&#xff1a;智能代码提示词生成 PromptCoder是一款利用人工智能技术的智能代码生成工具。它能够识别设计图或截图&#xff0c;并自动生成与之匹配的前端代码。无论是…