如何在滚动React js上添加元素中的类

har*_*rry 7 reactjs

如何在滚动React js中添加元素中的类,我想在滚动中添加类,如果在页面顶部则删除该类.

import React from "react"
import { Link } from "react-router"
import { prefixLink } from "gatsby-helpers"
import Helmet from "react-helmet"
import { config } from "config"

module.exports = React.createClass({
  propTypes() {
    return {
      children: React.PropTypes.any,
    }
  },
  render() {
  window.addEventListener('scroll', (event) => {

    });
    return (
      <div>
        <header className="header">
          <div className="top-bar">
            <span><a href="tel:6788272782">678-827-2782 </a></span>
            <span><a href="mailto:hellohello@knotel.com"> hellohello@knotel.com</a></span>
            <button>Login</button>
          </div>
        </header>
        {this.props.children}
      </div>
    )
  },

})
Run Code Online (Sandbox Code Playgroud)

zia*_*zia 19

如果你想在 2020 无状态组件中使用 React Hooks

const [scroll, setScroll] = useState(false);
 useEffect(() => {
   window.addEventListener("scroll", () => {
     setScroll(window.scrollY > 50);
   });
 }, []);
Run Code Online (Sandbox Code Playgroud)

并在代码中的任何地方使用它

className={scroll ? "bg-black" : "bg-white"}
Run Code Online (Sandbox Code Playgroud)

setScroll(window.scrollY > 50); 这里 50 指定高度。


Cha*_*nda 9

使用state来管理类名并在scroll事件中更新状态.此外,您应该将scroll事件绑定移动到componentDidMount函数而不是render.

import React from "react"
import { Link } from "react-router"
import { prefixLink } from "gatsby-helpers"
import Helmet from "react-helmet"
import { config } from "config"

module.exports = React.createClass({
  propTypes() {
    return {
      children: React.PropTypes.any,
    }
  },
  componentDidMount(){
      window.addEventListener('scroll', () => {
         let activeClass = 'normal';
         if(window.scrollY === 0){
             activeClass = 'top';
         }
         this.setState({ activeClass });
      });
  }
  render() {
    return (
      <div>
        <header className="header">
          <div className={`top-bar ${this.state.activeClass}`}>
            <span><a href="tel:6788272782">678-827-2782 </a></span>
            <span><a href="mailto:hellohello@knotel.com"> hellohello@knotel.com</a></span>
            <button>Login</button>
          </div>
        </header>
        {this.props.children}
      </div>
    )
  },

})
Run Code Online (Sandbox Code Playgroud)

  • @harry也不要忘记在componentWillUnmount中删除removeEventListener!componentWillUnmount(){window.removeEventListener('scroll'); } (2认同)