学无先后,达者为师

网站首页 编程语言 正文

react 利用antd-mobile实现楼层效果

作者:筱闯~ 更新时间: 2023-07-14 编程语言

首先是js模块

import React, { useEffect, useRef, useState } from 'react'
import { SideBar } from 'antd-mobile'
import  './louceng.css'
import { useThrottleFn } from 'ahooks'

const items = [
  { key: '1', title: '第一项', text: <div>12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项</div> },
  { key: '2', title: '第二项', text: <div>12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项</div> },
  { key: '3', title: '第三项', text: <div>12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项</div> },
  { key: '4', title: '第四项', text: <div>12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项</div> },
]

export default () => {
  const [activeKey, setActiveKey] = useState('1')

  const { run: handleScroll } = useThrottleFn(
    () => {
      let currentKey = items[0].key
      for (const item of items) {
        const element = document.getElementById(`anchor-${item.key}`)
        if (!element) continue
        const rect = element.getBoundingClientRect()
        if (rect.top <= 0) {
          currentKey = item.key
        } else {
          break
        }
      }
      setActiveKey(currentKey)
    },
    {
      leading: true,
      trailing: true,
      wait: 100,
    }
  )

  const mainElementRef = useRef()

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

  return (
    <div className="container" >
      <div className="side" >
        <SideBar
          activeKey={activeKey}
          onChange={key => {
            document.getElementById(`anchor-${key}`)?.scrollIntoView()
          }}
        >
          {items.map(item => (
            <SideBar.Item key={item.key} title={item.title} />
          ))}
        </SideBar>
      </div>
      <div className="main" ref={mainElementRef} style={{width:"100px"}}>
        {items.map(item => (
          <div style={{height:"600px"}} key={item.key}>
            <h2 id={`anchor-${item.key}`}>{item.title}</h2>
            {item.text}
          </div>
        ))}
      </div>
    </div>
  )
}

css样式

.container {
  height: 100vh;
  background-color: #ffffff;
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  /* [data-prefers-color='dark'] & {
        background-color: unset;
      } */
}

.side {
  flex: none;
}

.main {
  flex: auto;
  padding: 0 24px 32px;
  overflow-y: scroll;

}

h2 {
  margin: 0;
  padding: 12px 0;
}

实现效果

 

原文链接:https://blog.csdn.net/m0_64544033/article/details/131637702

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新