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;
相关推荐
阿蒙Amon1 小时前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习
hashiqimiya1 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
小a杰.1 小时前
Flutter 设计系统构建指南
开发语言·javascript·ecmascript
零度@2 小时前
Java中Map的多种用法
java·前端·python
yuanyxh2 小时前
静默打印程序实现
前端·react.js·electron
三十_A3 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
kgduu3 小时前
js之事件系统
javascript
小满zs4 小时前
Next.js第十三章(缓存组件)
前端
前端老宋Running4 小时前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
风止何安啊4 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试