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. });  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值