zoukankan      html  css  js  c++  java
  • [ReactJS] DOM Event Listeners in a React Component

    React doesn't provide the listener to listen the DOM event. But we can do it in React life cycle:

    So when the compoment did mount, we add listeners to the dom event.

    And remember to remove the dom listener when the compoment unmount.

    var Box = React.createClass({
      getInitialState:function(){
        return {
           window.innerWidth,
          scroll: document.body.scrollTop
        };
      },
      update: function(){
        this.setState({
           window.innerWidth,
          scroll: document.body.scrollTop
        })
      },
    
      componentDidMount:function(){
        window.addEventListener('resize', this.update);
        widnow.addEventListener('scroll', this.update);
      },
    
      componentWillUnmount:function(){
        window.removeEventListener('resize', this.update);
        window.removeEventListener('scroll', this.update);
      },
    
      render:function(){
        return <div>
          <p> {this.state.width}</p>
          <p>scroll: {this.state.scroll}</p>
        </div>;
      }
    });
    
    //React.render will be depricated in the next release
    //https://facebook.github.io/react/blog/2015/09/10/react-v0.14-rc1.html#two-packages-react-and-react-dom
    
    ReactDOM.render(<Box />, document.getElementById('box'));
  • 相关阅读:
    数据结构上机思考
    hdu1005,循环节
    网络赛总结
    icpc沈阳网络赛。cake cake!
    树的基础代码
    网络赛第一场
    欧拉函数
    欧拉函数
    多校第十场
    (环上)最大子段和
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5240753.html
Copyright © 2011-2022 走看看