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