简介
本文将会基于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