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'));
  • 相关阅读:
    【bzoj2115】[Wc2011] Xor
    【bzoj2460】[BeiJing2011]元素
    P2300 合并神犇 DP
    P1041 传染病控制 深搜
    P1038 神经网络 图论
    树状数组模板
    送外卖 状压DP
    士兵守卫(同P2016 战略游戏) 树形DP
    P1171 售货员的难题 喻队状压 DP
    P2062 分队问题 DP
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5240753.html
Copyright © 2011-2022 走看看