程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了基于滚动React JS的Toggle Class大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决基于滚动React JS的Toggle Class?

开发过程中遇到基于滚动React JS的Toggle Class的问题如何解决?下面主要结合日常开发的经验,给出你关于基于滚动React JS的Toggle Class的解决方法建议,希望对你解决基于滚动React JS的Toggle Class有所启发或帮助;

添加滚动侦听器的componentDIDMount()一种方法是使用生命周期方法。以下示例应给您一个想法:

import React from 'react';
import { render } from 'react-dom';

class App extends React.Component {
  state = {
    istop: true,
  };

  componentDIDMount() {
    document.addEventListener('scroll', () => {
      const istop = window.scrollY < 100;
      if (istop !== this.state.istop) {
          this.setState({ istop })
      }
    });
  }
  render() {
    return (
      <div style={{ height: '200vh' }}>
        <h2 style={{ position: 'fixed', top: 0 }}>Scroll {this.state.istop ? 'down' : 'up'}!</h2>
      </div>
    );
  }
}

render(<App />, document.getElementByID('root'));

当您的scrollY位置在100或更高位置时,这会将文本从“向下滚动”更改为“向上滚动”。

编辑:应避免过分更新每个滚动条上的状态。仅在布尔值更改时更新它。

解决方法

我正在使用bootstrap 4导航栏,并想在ig
400px向下滚动后更改背景颜色。我在查看react文档时发现了onScroll,但找不到太多信息。到目前为止,我有…

我不知道我是否使用了正确的事件侦听器或如何设置高度等。

而且我并没有真正设置内联样式…

  import React,{ Component } from 'react';

   class App extends Component {

   constructor(props) {
    super(props);

      this.state = {  scrollBackground: 'nav-bg' };
      this.handleScroll = this.handleScroll.bind(this);
   }


   handleScroll(){
      this.setState ({
         scrollBackground: !this.state.scrollBackground
       })
    }

 render() {
 const scrollBg = this.scrollBackground ? 'nav-bg scrolling' : 'nav-bg';

 return (
   <div>

       <Navbar inverse toggleable className={this.state.scrollBackground} 
                                  onScroll={this.handleScroll}>
        ...
      </Navbar>

    </div>
   );
  }
}

export default App;

大佬总结

以上是大佬教程为你收集整理的基于滚动React JS的Toggle Class全部内容,希望文章能够帮你解决基于滚动React JS的Toggle Class所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: