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;
相关推荐
胡斌附体13 分钟前
vue添加loading后修复页面渲染问题
前端·javascript·vue.js·渲染·v-if·异步加载
Dontla23 分钟前
Webpack DefinePlugin插件介绍(允许在编译时创建JS全局常量,常量可以在源代码中直接使用)JS环境变量
运维·javascript·webpack
酷爱码1 小时前
css中的 vertical-align与line-height作用详解
前端·css
沐土Arvin1 小时前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
专注VB编程开发20年1 小时前
VB.NET关于接口实现与简化设计的分析,封装其他类
java·前端·数据库
小妖6662 小时前
css 中 content: “\e6d0“ 怎么变成图标的?
前端·css
L耀早睡2 小时前
mapreduce打包运行
大数据·前端·spark·mapreduce
咖啡の猫2 小时前
JavaScript基础-创建对象的三种方式
开发语言·javascript·ecmascript
HouGISer2 小时前
副业小程序YUERGS,从开发到变现
前端·小程序
outstanding木槿3 小时前
react中安装依赖时的问题 【集合】
前端·javascript·react.js·node.js