SideBar 侧边导航与内容区域交互重写【Ant Design Mobile】

需求:SideBar 侧边导航与内容区域交互

  1. 点击侧边栏某一项时,相对应内容区域滚动到视口顶部
  2. 滚动视口区域,到某一项内容区域,侧边栏选中状态也会跟着变化
typescript 复制代码
const SideBarAgain: React.FC<PopupProps> = (props) => {

  // 父组件传过来的值
  const { tabList } = props

  const mainElementRef = useRef<HTMLDivElement>(null)
  // 用来监听页面滚动事件
  const scroll = useScroll(mainElementRef);

  const mainElement = mainElementRef.current

  const state = useReactive({ activeKey: '1' });

  const handleScroll = (key?:string) => {
    
    // 滚动时,需要修改侧边栏选中状态
    // 过滤出元素顶部到视窗的距离大于0的元素
    const currentKey = tabList.filter((item: { key: string })=>{
      const element = document.getElementById(`anchor-${item.key}`)
        if (!element) return
        const rect = element.getBoundingClientRect()
        if (rect.top >= 0) {
          return item
        }
    })
    
    // 判断如果currentKey大于0,则选取第一个key值
    if(currentKey.length){
      state.activeKey = currentKey[0].key
    }else{
      state.activeKey = tabList[tabList.length-1].key
    }
     
    // 点击侧边栏传入的ID,并滚动到对应位置
    if(key){
      document.getElementById(`anchor-${key}`)?.scrollIntoView({behavior: "smooth"})
      state.activeKey = key
    }
  }

  useEffect(() => {
    if (!mainElement) return
    mainElement.addEventListener('scroll', () => handleScroll)
    return () => {
      mainElement.removeEventListener('scroll', () => handleScroll)
    }
  }, [])

  // 利用scroll的变化监听handleScroll
  useLayoutEffect(() =>  handleScroll,[scroll])

  return (
       <div className='sider'>
          <SideBar activeKey={state.activeKey} onChange={(key)=>handleScroll(key)}>
            {tabList.map((item: { key: string, title: string }) => (
              <SideBar.Item key={item.key} title={item.title} />
            ))}
          </SideBar>
          <div className='main' ref={mainElementRef}>
            {tabList.map((item: { key: string; title: string; text: string}) => (
              <div key={item.key} id={`anchor-${item.key}`} >
                <h2>{item.title}</h2>
                {item.text}
              </div>
            ))}
          </div>
       </div>
  )
}

export default SideBarAgain;
相关推荐
像风一样自由20201 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
伍哥的传说2 小时前
React 各颜色转换方法、颜色值换算工具HEX、RGB/RGBA、HSL/HSLA、HSV、CMYK
深度学习·神经网络·react.js
aiprtem2 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊2 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术2 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing2 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止3 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall3 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴3 小时前
简单入门Python装饰器
前端·python
袁煦丞4 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作