亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在React.js中更新組件onScroll的樣式

在React.js中更新組件onScroll的樣式

蠱毒傳說 2019-11-25 15:22:07
我已經在React中構建了一個組件,該組件應該在窗口滾動時更新其自身的樣式以創建視差效果。組件render方法如下所示:  function() {    let style = { transform: 'translateY(0px)' };    window.addEventListener('scroll', (event) => {      let scrollTop = event.srcElement.body.scrollTop,          itemTranslate = Math.min(0, scrollTop/3 - 60);      style.transform = 'translateY(' + itemTranslate + 'px)');    });    return (      <div style={style}></div>    );  }這是行不通的,因為React不知道組件已更改,因此該組件不會重新渲染。我試過itemTranslate在組件狀態下存儲的值,并setState在滾動回調中調用。但是,這使滾動無法使用,因為這非常慢。關于如何做到這一點的任何建議?
查看完整描述

3 回答

?
DIEA

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

    });

},


查看完整回答
反對 回復 2019-11-25
?
慕雪6442864

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上的文檔。


查看完整回答
反對 回復 2019-11-25
?
滄海一幻覺

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

        >

我沒有任何性能問題。


查看完整回答
反對 回復 2019-11-25
  • 3 回答
  • 0 關注
  • 853 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號