class Test extends React.Component { constructor(props){ super(props); this.state = { top: 0 } this.handleWindowScroll = this.handleWindowScroll.bind(this); } handleWindowScroll() { this.setState({ top: document.body.scrollTop }) } componentDidMount() { window.addEventListener(‘scroll‘, this.handleWindowScroll); } componentWillUnmount() { window.removeEventListener(‘scroll‘, this.handleWindowScroll); } render() { return <div>{this.state.top}</div> } }
.
原文:https://www.cnblogs.com/crazycode2/p/12111696.html