react楼层效果

    // 模拟数据
    const data = Mock.mock({
  "list|20":[
    {
      "title":"@ctitle(3,5)",
       "id":"@id",
       "children|5-15":[{
         name:"@cname",
         img:"@Image(50x50,@color)",
         sonid:"@id"
       }]
    }
  ]
})

组件中

  import React from 'react'
import Appson from "../views/appson"
import Style from "../style/index.module.css" // css in js 
import {useState,useEffect,useRef} from "react"
import axios from 'axios'
const h3style = {
    background:"blue"
}
function App() {
let right = useRef(null)
let [arr,setArr] = useState([])
let [activeIndex,setActiveIndex] = useState(0)
useEffect(()=>{
    axios.get("/list").then(res=>{
        setArr(res.data)
    })

    setTimeout(()=>{
        window.addEventListener("scroll",handleSroll,true)
    },100)
},[])
const handleSroll = ()=>{
    // 获取右侧div滚动的位置
   //  right.current.children 是伪数组
   let topS = right.current.scrollTop
   console.log(topS,111);
   let arr = Array.from(right.current.children)
   console.log(arr)
   arr.forEach((item,index)=>{
        if (topS > item.offsetTop) {
            console.log(index,"index","我执行了几次");
            setActiveIndex(index)
         
        }
   })
}
const chanegIndex = (index)=>{
      setActiveIndex(index)
      console.log(right.current.children);
      right.current.children[index].scrollIntoView({behavior:'smooth'})
}
  return (
    <div className={Style.appwrap}>
        <div className={Style.left}>
            {
                arr && arr.length ? arr.map((item,index)=>{
                    return <h3 key={index} className={Style.h3 } onClick={()=>{chanegIndex(index)}} style={index===activeIndex?h3style:null}>{item.title}</h3>
                }):"暂无数据"
            }
        </div>
        <div className={Style.right} ref={right}>
            {
                 arr && arr.length ? arr.map((item,index)=>{
                    return (
                        <div key={index}>
                            <h3>{item.title}</h3>
                            <div style={{height:"200px",background:"red"}}></div>
                        </div>
                    )
                }):"暂无数据"
            }
        </div>
       
    </div>
  )
}

export default App
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容