简体   繁体   English

在 React 中实现多行面包屑链接的最佳方法是什么?

[英]What is best way to implement multi line bread crumb links in react?

I am trying to implement a multiline breadcrumb links for mobile/tablet devices.我正在尝试为移动/平板设备实现多行面包屑链接。 User will be navigating through multiple folders and if it exceeds the max lines configured of breadcrumb link container I am dropping out links from beginning (trying to show maximum path from current path).用户将浏览多个文件夹,如果它超过面包屑链接容器配置的最大行数,我将从头开始删除链接(试图显示当前路径的最大路径)。 Couldn't find a css method for this.找不到为此的 css 方法。 Please find an example below with max line = 2请在下面找到max line = 2的示例

current path = 
path1 / path2 
/ path3 / path4
/path5

exceeds at path5 (went to 3rd line should update the link to超过 path5(去到第 3 行应该更新链接到

updated path = 
.../ path2 
/ path3 / path4

if user navigates back should updates without the ellipse.如果用户向后导航,则应该在没有省略号的情况下进行更新。 I tried the below methods, didn't work out as expected -我尝试了以下方法,没有达到预期效果 -

  1. css way to clamp to max lines // it didn't work since we need to find how many links to trim限制最大行数的 css 方法 // 它不起作用,因为我们需要找到要修剪的链接数
  2. Using white-space: no wrap and text-overflow: ellipse , I can't use it since it wont allow multiline使用white-space: no wraptext-overflow: ellipse ,我不能使用它,因为它不允许多行
  3. tried to find maximum number of characters fit in a single line of div using expression - Width(in pixel) * Font Constant / font Size (in pixels)尝试使用表达式找到适合单行 div 的最大字符数 - Width(in pixel) * Font Constant / font Size (in pixels)

Figured out width and font size dynamically.动态计算出宽度和字体大小。 but couldn't figure out how to get the font constant of an element.但无法弄清楚如何获取元素的字体常量。 Any help, greatly appreciated.任何帮助,不胜感激。

I created a demo component here.我在这里创建了一个演示组件。 Hope it will be helpful.希望它会有所帮助。
The strategy I'm using here is:我在这里使用的策略是:

  1. Count lines by dividing the height of the wrapper by the line height通过将包装器的高度除以行高来计算行数
  2. Remove items from the beginning until the number of lines is reduced to the maximum allowed从头开始删除项目,直到行数减少到允许的最大值

Breadcrumbs.js面包屑.js

import { createRef, useEffect, useState } from "react";
import "./Breadcrumbs.css";

function Breadcrumbs() {

    const wrapper = createRef();
    const ellipsis = createRef();
    const [items, setItems] = useState([]);
    const [dropped, setDropped] = useState(false);

    const countLines = (element, lineHeight) => {
        let height = element.offsetHeight;
        let lines = height / lineHeight;
        return Math.round(lines);
    }

    useEffect(() => {
        setItems(window.location.pathname.split("/").filter((e) => e.length > 0))
    }, [window.location.pathname])

    useEffect(() => {
        const lines = countLines(wrapper.current, ellipsis.current.clientHeight);
        const maxLines = 2;

        if (lines > maxLines) {
            setItems(items.slice(1));
            setDropped(true);
        }
    }, [items])

    return <nav className="breadcrumbs-wrapper" ref={wrapper}>
        <span ref={ellipsis}>
            {dropped ? "..." : ""}
        </span>
        {items.map((item, index) => {
            return <span key={index.toString()}>
                <span>&nbsp;/&nbsp;</span>
                <a href="#">{item}</a>
            </span>
        })}
    </nav>
}

export default Breadcrumbs;

Breadcrumbs.css面包屑.css

.breadcrumbs-wrapper {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

Here are screenshots of the working example这是工作示例的屏幕截图

一行没有换行

两条线

多于两行

import React from 'react';从“反应”导入反应; import { Link, useLocation } from 'react-router-dom';从'react-router-dom'导入{Link,useLocation};

const Breadcrumb = ({ handleDrawerOpen, open }) => {
   const { pathname } = useLocation();

   const pathName = (paths, index) => {
      return paths.filter((path, pathIndex) => pathIndex !== 0 && pathIndex <= index).join('/');
   };
   
   const func = () => {
      const paths = pathname.split('/');
      return paths.map(
         (path, index) =>
            index !== 0 && (
               <Link
                  style={{
                     textDecoration: 'none',
                     color: index === paths.length - 1 ? '#49C5B6' : 'white',
                  }}
                  to={`/${pathName(paths, index)}`}>{`${
                  path?.charAt(0)?.toUpperCase() + path.slice(1).toLowerCase()
               } ${index !== paths.length - 1 ? '>' : ''} `}</Link>
            )
      );
   };
   return (
      <Box>
         {!open && (
            <IconButton onClick={handleDrawerOpen}>
               <MenuIcon />
            </IconButton>
         )}

         <Profile />
      </Box>
   );
};

export default Breadcrumb;

You can slice last 5 items and map through them to render the links:您可以切片最后 5 个项目并映射它们以呈现链接:

breadcrumbs.slice(-5).map((breadcrumb, index) => (
<React.Fragment key={index}>
  {index !== 0 && breadcrumbs.length > 1 ? ' / ' : ''}
  {index === 0 && breadcrumb.path !== breadcrumbs[0].path ? (
    '...'
  ) : (
    <a href={breadcrumb.link}>{breadcrumb.path}</a>
  )}
  {index % 2 ? <br /> : ''}
</React.Fragment>

Here's a demo representing your requirement.这是一个代表您的要求的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何实现类似于Facebook的面包屑导航? - How do I implement bread-crumb navigation similar to Facebook? React Native Maps:实现可拖动标记的最佳方法是什么? - React Native Maps: What's the best way to implement a draggable marker? 实现链接 yii2 -&gt; React js 的最佳方法是什么? - What is the best way to implement a link yii2 -> React js? 在页面上禁用链接的最佳方法是什么? - What is the best way to disable links when on page? 在 React 中实现动态输入数组的最佳方法 - Best way to implement dynamic array of inputs in React 在 React 应用程序中使用访问令牌实现身份验证的最佳方法是什么? - What could be the best way to implement authentication using access token in React app? 在 Quasar 中实现双重验证的最佳方法是什么? - What is the best way to implement double validation in Quasar? 在 React Redux 中实现撤消状态更改(撤消存储/历史实现)的最佳方法是什么 - What is the best way to implement undo state change (undo store/history implementation) in React Redux 在 reactJS 中实现列表水平滚动的最佳方法是什么? 我也可以在反应代码中使用 getElementById 吗? - What is the best way to implement horizontal scroll on list in reactJS? And also can i use getElementById in react code? OR和AND条件未按预期返回-实施它的最佳方法是什么? - OR and AND conditions not returning as expected - What is best way to implement it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM