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

92 阅读2分钟

1.首先是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:

12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项
},

  { key: '2', title: '第二项', text:

12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项
},

  { key: '3', title: '第三项', text:

12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项
},

  { key: '4', title: '第四项', text:

12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项12313212313第一项
},

]

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 (

   

     

        <SideBar

          activeKey={activeKey}

          onChange={key => {

            document.getElementById(anchor-${key})?.scrollIntoView()

          }}

        >

          {items.map(item => (

            <SideBar.Item key={item.key} title={item.title} />

          ))}

       

     

      <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}

            {item.text}

         

        ))}

     

   

  )

}

2.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;

}

3.实现效果: