注意:
這篇文章是講如何給 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 結(jié)構(gòu)的時候被調(diào)用。通常情況下,你可以在這綁定普通的 DOM 事件。
注意,事件的回調(diào)被綁定在了 react 組件上,而不是原始的元素上。React 通過一個 autobinding 過程自動將方法綁定到當前的組件實例上。