React 实现吸顶效果

2,080 阅读1分钟
import React from 'react';
import ReactDOM from "react-dom";

const fixedTopStyle = {
    position:'fixed',top:0,left: 0,zIndex: 100, width: '100%',
}

export default class FixedTop extends React.Component{

    constructor(){
        super(...arguments);
        this.state={
            fixedTop:false
        };
        this.node = null;
    }

    componentDidMount(){
        window.document.onscroll=()=>{
            const scrollTop = window.document.body.scrollTop || window.document.documentElement.scrollTop;
            const domNode = ReactDOM.findDOMNode(this.node);
            if(domNode){
                this.setState({ fixedTop: scrollTop > domNode.offsetTop });
            }
        }
    }

    render(){
        return(
            <div ref={node=> this.node = node} 
                 style={ this.state.fixedTop? fixedTopStyle : null} >
                {this.props.children}
            </div>
        );
    }
}
 <FixedTop>
    <div></div> 
  </FixedTop>