react页面滚动监控(hooks,componentDidMount)
标签搜索
侧边栏壁纸
博主昵称
2c

  • 累计撰写 19 篇文章
  • 累计收到 12 条评论

react页面滚动监控(hooks,componentDidMount)

2c
2c
2022-04-28 / 0 评论 / 8 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年05月23日,已超过702天没有更新,若内容或图片失效,请留言反馈。

componentDidMount声明周期版本

import React, { Component } from 'react'

interface Props {

}
interface State {

}

export default class index extends Component<Props, State> {
    state = {}

    render() {
        return (
            <div>

            </div>
        )
    }
    componentDidMount(){
        window.addEventListener('scroll', this.handleScroll);    
      }

      handleScroll(){
        console.log(window.scrollY)
      }
}

hooks版本


import React, { ReactElement, useEffect } from 'react'
import './index.css'

interface Props {

}

export default function Main(: Props): ReactElement {
    const [windowSize, setWindowSize] = React.useState({ width: 0, height: 0 })
 
    const windowChange = () => {
        const width = window.scrollX
        const height = window.scrollY
        setWindowSize({ width, height })
        console.log(height)
    }
 
    useEffect(() => {
        windowChange()
        window.addEventListener('scroll', windowChange)
 
        return () => {
            window.removeEventListener('scroll', windowChange)
        }
    }, [])


    return (
        <div className='maindiv'>
            Main
        </div>
    )

}
0

评论 (0)

取消