React - 实现菜单栏滚动

简介

        本文将会基于react实现滚动菜单栏功能。

技术实现

实现效果

       点击菜单,内容区域会自动滚动到对应卡片。内容区域滑动,指定菜单栏会被选中。

ScrollMenu.js
import {useRef, useState} from "react";
import './ScrollMenu.css';

export const ScrollMenu = ({products}) => {
    // 获取 categoryProductMap
    const categoryProductMap = new Map();
    products.forEach(product => {
        const category = product.category;
        let categoryProductList = categoryProductMap.get(category);
        if (!categoryProductList) {
            categoryProductList = [];
        }
        categoryProductList.push(product);
        categoryProductMap.set(category, categoryProductList);
    });

    // 获取类别列表
    const categoryList = Array.from(categoryProductMap.keys());

    // 菜单选中索引
    const [current, setCurrent] = useState(0);

    /**
     * 内容引用
     */
    const contentRef = useRef();

    /**
     * 当左侧菜单点击时候
     */
    const onMenuClick = (idx) => {
        if (idx !== current) {
            // 内容自动滚动到对应菜单位置
            contentRef.current.scrollTop = height.slice(0, idx).reduce((a, b) => a + b, 0);
            setCurrent(idx);
        }
    }

    /**
     *  计算右侧商品类别卡片高度
     */
    const height = [];
    const itemHeight = 25;
    categoryList.forEach((category, index) => {
        var productCnt = categoryProductMap.get(category).length;
        height.push((productCnt + 1) * itemHeight); // 0.8 是header高度
    });

    console.log(height)
    /**
     * 当右侧内容滚动时候
     */
    const onContentScroll = () => {
        const scrollTop = contentRef.current.scrollTop;
        if (current < height.length - 1){
            const nextIdx = current + 1;
            // 计算下一个位置高度
            const nextHeight = height.slice(0, nextIdx).reduce((a, b) => a + b, 0);
            console.log('scrollTop', scrollTop, 'nextHeight', nextHeight, 'nextIdx', nextIdx)
            if (scrollTop >= nextHeight) {
                contentRef.current.scrollTop = nextHeight;
                setCurrent(nextIdx);
                return;
            }
        }
        if (current > 0) {
            const lastIdx = current - 1;
            // 计算上一个位置高度
            const lastHeight = height.slice(0, lastIdx).reduce((a, b) => a + b, 0);
            console.log('scrollTop', scrollTop, 'lastHeight', lastHeight, 'lastIdx', lastIdx)
            if (scrollTop <= lastHeight) {
                contentRef.current.scrollTop = lastHeight;
                setCurrent(lastIdx);
                return;
            }
        }

    }

    return (
        <div className='scroll-menu'>
            <div className='menu'>
                {
                    // 菜单列表
                    categoryList.map((category, index) => {
                        return (
                            <div className={"menu-item" + ((index === current )? '-active' : '')}
                                 key={`${index}`} id={`menu-item-${index}`}
                                 onClick={(event) => {
                                     onMenuClick(index)
                                 }}>
                                {category}
                            </div>
                        )
                    })
                }
            </div>
            <div className='content' ref={contentRef} onScroll={(event) => {
                onContentScroll()
            }}>
                {
                    categoryList.map((category, index) => {
                        // 获取类别商品
                        const productList = categoryProductMap.get(category);
                        return (
                            <div key={index}>
                                <div className='content-item-header' key={`${index}`}
                                     id={`content-item-${index}`} style={{
                                    height: itemHeight
                                }} >{category}</div>
                                {
                                    productList.map((product,idx) => {
                                        return <div className='content-item-product'style={{
                                            height: itemHeight
                                        }}  key={`${index}-${idx}`} >{product.name}</div>
                                    })
                                }
                            </div>
                        )
                    })
                }
            </div>
        </div>


    )
}
ScrollMenu.css
.scroll-menu {
    display: flex;
    flex-direction: row;
    width: 300px;
    height: 100px;
}

.menu{
    width: 90px;
    height: 100px;
    display: flex;
    flex-direction: column;
}

.menu-item {
    text-align: center;
    vertical-align: middle;

}

.menu-item-active {
    text-align: center;
    vertical-align: middle;
    background-color: lightcoral;
}

.content {
    width: 210px;

    overflow: auto;
}

.content-item-header{
    text-align: left;
    vertical-align: top;
    background-color: lightblue;
}

.content-item-product{
    text-align: center;
    vertical-align: center;
    background-color: lightyellow;
}
App.js
import './App.css';
import {ScrollMenu} from "./component/scroll-menu/ScrollMenu";

const App = ()=> {
    const products = [
        {
            category:'蔬菜',
            name:'辣椒'
        },
        {
            category:'蔬菜',
            name:'毛豆'
        },
        {
            category:'蔬菜',
            name:'芹菜'
        },
        {
            category:'蔬菜',
            name:'青菜'
        },
        {
            category:'水果',
            name:'苹果'
        },
        {
            category:'水果',
            name:'梨'
        },
        {
            category:'水果',
            name:'橘子'
        },   {
            category:'食物',
            name:'肉'
        },   {
            category:'食物',
            name:'罐頭'
        }
        ,   {
            category:'食物',
            name:'雞腿'
        }
    ];

    return (
        <ScrollMenu products={products}/>
    )
}



export default App;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/469505.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【MATLAB源码-第165期】基于matlab的科莫多巨蜥算法(KMA)机器人栅格路径规划,输出做短路径图和适应度曲线。

操作环境&#xff1a; MATLAB 2022a 1、算法描述 科莫多巨蜥算法&#xff08;Komodo Mlipir Algorithm&#xff0c;简称KMA&#xff09;是一种受到印尼科莫多岛上独特生物——科莫多巨蜥启发的创新算法。尽管这个算法的名称听起来很有趣&#xff0c;但实际上它并不是一个公认…

写论文matplotlib使用同一色系的颜色

推荐网站 Colorsinspo - All in one resource for finding everything about colors | Colorsinspo 网页直接可以复制颜色 除此之外&#xff0c;自己还试了一个色系&#xff08;可惜不理想&#xff0c;看着不均匀&#xff09;&#xff0c;先存到这里 color_name [lightgr…

数据结构从入门到精通——直接插入排序

直接插入排序 前言一、直接插入排序的基本思想&#xff1a;二、直接插入排序的实例三、直接插入排序的动图展示四、直接插入排序的具体代码test.c 前言 直接插入排序是一种简单的排序算法&#xff0c;其工作原理是逐个将待排序元素插入到已排序序列中的适当位置&#xff0c;直…

7-初识Keras:轻松完成神经网络模型搭建

声明 本文章基于哔哩哔哩付费课程《小白也能听懂的人工智能原理》。仅供学习记录、分享&#xff0c;严禁他用&#xff01;&#xff01;如有侵权&#xff0c;请联系删除 目录 一、知识引入 &#xff08;一&#xff09;矩阵和向量 1、向量 2、矩阵 &#xff08;二&#xff…

java Flink(四十三)Flink Interval Join源码解析以及简单实例

背景 之前我们在一片文章里简单介绍过Flink的多流合并算子 java Flink&#xff08;三十六&#xff09;Flink多流合并算子UNION、CONNECT、CoGroup、Join 今天我们通过Flink 1.14的源码对Flink的Interval Join进行深入的理解。 Interval Join不是两个窗口做关联&#xff0c;…

001_【基础篇】SpringBoot入门案例创建与实现

要求&#xff1a;使用 Springboot 开发一个 web 程序&#xff0c;浏览器发起请求/hello后&#xff0c;给浏览器返回字符串 hello springboot 使用 springboot 只需要引入一个起步依赖 <dependency><groupId>org.springframework.boot</groupId><artifac…

STP环路避免实验(思科)

华为设备参考&#xff1a;STP环路避免实验&#xff08;华为&#xff09; 一&#xff0c;技术简介 Spanning Tree Protocol&#xff08;STP&#xff09;&#xff0c;即生成树协议&#xff0c;是一种数据链路层协议。主要作用是防止二层环路&#xff0c;并自适应网络变化和故障…

个人网站制作 Part 9 添加发布、管理博客功能 | Web开发项目

文章目录 &#x1f469;‍&#x1f4bb; 基础Web开发练手项目系列&#xff1a;个人网站制作&#x1f680; 添加博客功能&#x1f528;使用Express和MongoDB&#x1f527;步骤 1: 创建博客模型&#x1f527;步骤 2: 创建博客路由 &#x1f528;使用前端框架&#x1f527;步骤 3:…

什么是零日攻击?

一、零日攻击的概念 零日攻击是指利用零日漏洞对系统或软件应用发动的网络攻击。 零日漏洞也称零时差漏洞&#xff0c;通常是指还没有补丁的安全漏洞。由于零日漏洞的严重级别通常较高&#xff0c;所以零日攻击往往也具有很大的破坏性。 目前&#xff0c;任何安全产品或解决方案…

OxyPlot 导出图片

在 OxyPlot 官方文档 https://oxyplot.readthedocs.io/en/latest/export/index.html 中查看 这里用到的是导出到 PNG 文件的方法&#xff0c;不过用的 NuGet 包最新版&#xff08;2.1.0&#xff09;中&#xff0c;PngExporter 中并没有 Background 属性&#xff1a; 所以如果图…

字符函数与字符串函数

前言 本次博客可以说内容最为多的一次博客&#xff0c;讲解同样很细致大家好好看看 1字符函数 在讲解字符函数时,大家得了解什么是字符吧 普通字符a b c 1 转义字符 \n 换行‘ \t’ 水平制表符\r回车 大家了解即可 在C语言中字符也可以有分类 所以我们先来看看…

软件测试经验与教训

大概在18年的时候&#xff0c;就看过《软件测试经验与教训》的纸制版&#xff0c;里面的一些观点深刻的影响了我&#xff0c;也影响了后来我对测试的思考。最近又一次快速阅读了电子版&#xff0c;还是收获满满。下面精选出10条&#xff0c;和大家分享。 一、测试人员是项目的…

testng测试类第2步

创建xml文件并编写xml文件 并学习其中的参数 1、创建 xml文件 在测试包->右键找到creat TestNG XML 创建xml文件 如果报错就可以粘贴过来 认识原始文件 这里首行是标识&#xff0c;其次是2个参数&#xff0c;name是测试套件的名称&#xff0c;谁的测试套件一般是公司名称…

JAVA实战手册-开篇总述

该专题以实战为出发点&#xff0c;总结概述了实际工作中常用的java知识点&#xff0c;掌握了这些知识点&#xff0c;日常工作开发以及面试都不在话下。 话不多说&#xff0c;直入正题&#xff0c;以下为JAVA知识点概括总结&#xff08;总计涵盖了10大类78小项&#xff09; 针对…

AcWing 727. 菱形——像拼图一样做题

题目描述] 分析&#xff1a; 利用程序根据输入的整数&#xff0c;画出由字符*构成的该整数阶的实心菱形。给出一个示例&#xff1a; n 7 n7 n7。 * * * * * * * * * * * * * * * * * * * * * * * * * 我们将采取拆解问题&#xff0c;通过四个部分的…

Linux编程4.7 网络编程-套接字与地址

1、因特网地址结构 struct in_addr{in_addr_t s_addr; /*ipv4地址*/ }struct sockaaddr_in{short int sin_family; /*Internet地址族&#xff0c;如AF_INET&#xff08;主机字节序&#xff09;*/ unsigned short int sin_port; /*端口号&#xff0c;16…

upload-labs第二关第五关

upload-labs第二关 1、先上传个马试试&#xff0c;看看页面显示什么&#xff0c;要先把上次上传的马删掉哦 2、提示文件类型不正确&#xff0c;在看下提示说是在服务端做了检查 3、那就上传个php格式的&#xff0c;然后呢bp抓包把文件格式改了 4、修改后的 5、修改后发现不…

【物联网】Modbus 协议及应用

Modbus 协议简介 QingHub设计器在设计物联网数据采集时不可避免的需要针对Modbus协议的设备做相关数据采集&#xff0c;这里就我们的实际项目经验分享Modbus协议 简介 Modbus由MODICON公司于1979年开发&#xff0c;是一种工业现场总线协议标准。1996年施耐德公司推出基于以太…

ansible 运维自动化

pxe 一键安装操作系统 操作系统只是提供一个平台 lnmp 需要多软件协同完成的一个简单项目 服务器正常运行 日常运维 巡检 服务器上的软件正常运行 zabbix 普罗米修斯 系统调优&#xff0c;架构调优 前言 运维自动化 云计算核心职能 搭建平台架构 …
最新文章