2017-05-26 65 views
0

如何在滚动元素中添加类React js,我想在滚动中添加类并在页面顶部移除该类。如何在滚动元素上添加类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:[email protected]"> [email protected]</a></span> 
      <button>Login</button> 
      </div> 
     </header> 
     {this.props.children} 
     </div> 
    ) 
    }, 

}) 

回答

1

使用状态来管理滚动事件中的类名和更新状态。另外,您应该将滚动事件绑定移到componentDidMount函数中,而不是渲染。

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', (event) => { 
     if(//scroll position is top){ 
      class = 'top'; 
     }else{ 
      class = 'normal'; 
     } 
     this.setState({ 
      activeClass: class 
     }) 
     }); 
    } 
    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:[email protected]"> [email protected]</a></span> 
      <button>Login</button> 
      </div> 
     </header> 
     {this.props.children} 
     </div> 
    ) 
    }, 

}) 
+0

谢谢@Chase DeAnda – harry