react---项目中的注意事项(1)
1:react监听页面滚动事件
首先是在页面中,当元素加载之前和加载之后,绑定滚动事件。
constructor(props) {
super(props);
this.state = {
site: false,
};
}
componentWillMount() {
window.addEventListener('scroll', this.scroll.bind(this));
}
componentDidMount() {
window.addEventListener('scroll', this.scroll.bind(this));
}
scroll() {
const scrollTop = window.scrollTop;
const headerHeight = 100;
if (scrollTop >= headerHeight) {
this.setState({ site: true });
} else {
this.setState({ site: false });
}
}
这里会出现一个问题,就是当页面跳转时,该事件没有被解除,在其他页面进行页面滚动时,会报错。因为获取不到页面元素header的高度,所以当离开该页面的时候,需要解除绑定事件。
componentWillUnmount() {
window.removeEventListener('scroll', this.scroll.bind(this));
}
这时会发现,这个并没有其效果,原因在于我们是在事件中绑定的this,这里每次都是一个新的对象,因此没办法解除我们一开始绑定的事件对象。
于是将代码更改为
constructor(props) {
super(props);
this.state = {
site: false,
};
this.scroll = this.scroll.bind(this);
}
componentWillMount() {
window.addEventListener('scroll', this.scroll);
}
componentDidMount() {
window.addEventListener('scroll', this.scroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scroll);
}
handleScroll() {
const scrollTop = document.body.scrollTop;
const headerHeight = 100;
if (scrollTop >= headerHeight) {
this.setState({ sidebarFixed: true });
} else {
this.setState({ sidebarFixed: false });
}
}
好了,将事件在构造函数中绑定好,然后调用和解除的都是同一对象。

浙公网安备 33010602011771号