React 中 mixin的作用

1.mixin的作用是抽离公共功能,不存在渲染dom的需要,所以它没有render方法。如果你定义了render方法,那么他会和组件的render方法冲突而报错。

2.mixin不应该污染state,所以他也没有 setState 方法。

3.mixin应该只提供接口(即方法),不应该提供任何属性。

TimerMixin

  1. var TimerMixin = function() {  
  2. return {  
  3. componentDidMount: function() {  
  4. this._interval = setInterval(this._onTick, 1000);  
  5. },  
  6. format: function(d) {  
  7. return d >= 10 ? d : ("0"+d);  
  8. },  
  9. _onTick: function() {  
  10. var d = new Date();  
  11. this.timerTick(this.format(d.getHours()) + ":" + this.format(d.getMinutes()) + ":" + this.format(d.getSeconds()));  
  12. },  
  13. componentWillUnmount: function() {  
  14. clearInterval(this._interval);  
  15. }  
  16. }  
  17. }  
  18. var Card = React.createClass({  
  19. mixins: [  
  20. TimerMixin()  
  21. ],  
  22. timerTick: function(t) {  
  23. this.setState({  
  24. time: t  
  25. });  
  26. },  
  27. getInitialState: function() {  
  28. return {  
  29. time: 'loading time'  
  30. }  
  31. },  
  32. render: function() {  
  33. return (  
  34. <div>Hello {this.props.name}! It is {this.state.time} !</div>  
  35. );  
  36. }  
  37. });  

猜你喜欢

转载自helldancer.iteye.com/blog/2309771