[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'));
原文地址:https://www.cnblogs.com/Answer1215/p/5240753.html