2017-10-19 54 views
0

我知道这个问题已经回答了很多次,但我的挑战是奇特的,因为我已经尝试了所有的答案,但没有运气。 这里是我的代码Reactjs onScroll event not responding

export default class scrollLogic extends Component{ 
    constructor(props) { 
     super(props); 
     this.state={ 
      scroll:false 
     }; 
     this.scrollDetector=this.scrollDetector.bind(this) 
    } 

    scrollDetector(ev) { 
     console.log("Scrolling!"); 
    } 
    componentDidMount() { 
     const list = ReactDOM.findDOMNode(this.refs.list) 
     list.addEventListener('scroll', this.scrollDetector); 
    } 
    componentWillUnmount() { 
     const list = ReactDOM.findDOMNode(this.refs.list) 
     list.removeEventListener('scroll', this.scrollDetector); 
    } 
render() { 
     return (
      <div ref="list" className="header-holder"></div> 
) 
} 
} 

回答

0

我意识到onScroll事件应该只用于容器本身有一个滚动条,所以使用window.addEventListener('scroll', this.scrollDetector)代替解决了这个问题。它听取窗口本身的滚动而不是div。

,所以我已经格式化我的代码看起来像这样

export default class scrollLogic extends Component{ 
    constructor(props) { 
     super(props); 
     this.state={ 
      scroll:false 
     }; 
     this.scrollDetector=this.scrollDetector.bind(this) 
    } 

    scrollDetector() { 

     this.setState({ 
       scroll:true 
     }) 
    } 
    componentDidMount() { 
     const list = ReactDOM.findDOMNode(this.refs.list) 
     window.addEventListener('scroll', this.scrollDetector); 
    } 
    componentWillUnmount() { 
     const list = ReactDOM.findDOMNode(this.refs.list) 
     window.removeEventListener('scroll', this.scrollDetector); 
    } 
render() { 
     return (
      (this.state.scroll)? <HeaderMin/>:<HeaderMax/> 
) 
} 
} 

我希望这可以帮助别人..

0

我想这个问题是您正在使用componentDidMount方法的组件已经呈现后调用。尝试使用componentWillMount而不是使用componentDidMount