codecamp

组件的 DOM 事件监听

注意:

这篇文章是讲如何给 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 渲染完成且已经有了 DOM 结构的时候被调用。通常情况下,你可以在这绑定普通的 DOM 事件。

注意,事件的回调被绑定在了 react 组件上,而不是原始的元素上。React 通过一个 autobinding 过程自动将方法绑定到当前的组件实例上。


getInitialState 里的 Props 是一个反模式
通过 AJAX 加载初始数据
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }