【问题标题】:how to change css of permanent item when scroll using react使用反应滚动时如何更改永久项目的css
【发布时间】:2018-02-05 21:34:15
【问题描述】:

我如何在使用 react 时更改 div 的滚动高度???

<div id="navigation"></div>

css:

#navigation{
  background: #fff;
  position: fixed;
  width:100%;
  height:60px;
  text-align: center;
  direction: rtl;
}

【问题讨论】:

  • 让你的问题更清晰
  • 使用 jquery 来改变 div 的高度将不得不使用 add 类,这不能用于反应。 @artgb

标签: javascript jquery css reactjs


【解决方案1】:

您可以使用带有事件侦听器的纯 Javascript。根据滚动的距离更改状态并切换类。这是一个例子:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      hasScrolled: false,
    };
    this.handleScroll = this.handleScroll.bind(this);
  }

  handleScroll() {
    let hasScrolled = true;

    // Check if it was scrolled back to the top.
    if (document.body.scrollTop <= 20) {
      hasScrolled = false;
    }

    this.setState({ hasScrolled });
  }

  componentDidMount() {
    // Listen on scrolling event, call our function.
    window.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount() {
    // Unlisten if the component unmounts.
    window.removeEventListener('scroll', this.handleScroll);
  }

  render() {
    // Add className to the navigation based on our state.
    return (
      <div>
        <div
          id="navigation"
          className={this.state.hasScrolled ? 'onscroll' : null}
        />

        <p>
          Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
          nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
          sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
          rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem
          ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur
          sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
          dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam
          et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea
          takimata sanctus est Lorem ipsum dolor sit amet.
        </p>
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('root'));
#navigation {
  background: red;
  position: fixed;
  top: 0;
  width: 100%;
  height: 60px;
  text-align: center;
  direction: rtl;
  transition: .2s ease height;
}

#navigation.onscroll {
  height: 30px;
}

p {
  margin: 80px 20px;
  font-size: 34px;
  font-family: system-ui, sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

  • 如何将其添加到此处? @fabian schultz
    ) } }); ReactDOM.render( , document.getElementById('navigation-bar') );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 2014-02-14
  • 1970-01-01
相关资源
最近更新 更多