3 回答

TA貢獻1820條經驗 獲得超2個贊
您應該在中綁定偵聽器componentDidMount,這樣,偵聽器僅創建一次。您應該能夠將樣式存儲在狀態中,偵聽器可能是導致性能問題的原因。
像這樣:
componentDidMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function(event) {
let scrollTop = event.srcElement.body.scrollTop,
itemTranslate = Math.min(0, scrollTop/3 - 60);
this.setState({
transform: itemTranslate
});
},

TA貢獻1812條經驗 獲得超5個贊
為了幫助這里的任何人,在使用Austins答案時注意到緩慢的行為/性能問題,并想要使用注釋中提到的ref的示例,以下是我用于切換類的上/下圖標的示例:
在render方法中:
<i ref={(ref) => this.scrollIcon = ref} className="fa fa-2x fa-chevron-down"></i>
在處理程序方法中:
if (this.scrollIcon !== null) {
if(($(document).scrollTop() + $(window).height() / 2) > ($('body').height() / 2)){
$(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-up');
}else{
$(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-down');
}
}
并按照奧斯汀提到的方式添加/刪除處理程序:
componentDidMount(){
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount(){
window.removeEventListener('scroll', this.handleScroll);
},
refs上的文檔。

TA貢獻1824條經驗 獲得超5個贊
我制作響應式導航欄的解決方案(位置:不滾動時為“相對”,滾動時且不在頁面頂部時為固定)
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
if (window.scrollY === 0 && this.state.scrolling === true) {
this.setState({scrolling: false});
}
else if (window.scrollY !== 0 && this.state.scrolling !== true) {
this.setState({scrolling: true});
}
}
<Navbar
style={{color: '#06DCD6', borderWidth: 0, position: this.state.scrolling ? 'fixed' : 'relative', top: 0, width: '100vw', zIndex: 1}}
>
我沒有任何性能問題。
添加回答
舉報