組件的 DOM 事件監(jiān)聽

2019-08-14 14:31 更新

注意:

這篇文章是講如何給 DOM 元素綁定 React 未提供的事件 (check here for more info。 當你想和其他類庫比如 jQuery 一起使用的時候,需要知道這些。

Try to resize the window:

var Box = React.createClass({
  getInitialState: function() {    return {windowWidth: window.innerWidth};
  },

  handleResize: function(e) {    this.setState({windowWidth: window.innerWidth});
  },

  componentDidMount: function() {    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount: function() {    window.removeEventListener('resize', this.handleResize);
  },

  render: function() {    return <div>Current window width: {this.state.windowWidth}</div>;
  }
});

React.render(<Box />, mountNode);

componentDidMount 會在 component 渲染完成且已經(jīng)有了 DOM 結構的時候被調(diào)用。通常情況下,你可以在這綁定普通的 DOM 事件。

注意,事件的回調(diào)被綁定在了 react 組件上,而不是原始的元素上。React 通過一個 autobinding 過程自動將方法綁定到當前的組件實例上。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號