作用是操作dom
场景:图片加载完以后获取图片的宽高
// window上添加事件监听后,组件销毁前需要移除
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
时间: 2024-11-05 03:21:56