码迷,mamicode.com
首页 > 其他好文 > 详细

React Mixins

时间:2017-08-24 10:39:05      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:tin   ever   define   mixin   get   initial   har   target   https   

React Mixins

  ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes.  

  We also found numerous issues in codebases using mixins, and don‘t recommend using them in the new code.

技术分享
var SetIntervalMixin = {
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.forEach(clearInterval);
  }
};

var createReactClass = require(‘create-react-class‘);

var TickTock = createReactClass({
  mixins: [SetIntervalMixin], // Use the mixin
  getInitialState: function() {
    return {seconds: 0};
  },
  componentDidMount: function() {
    this.setInterval(this.tick, 1000); // Call a method on the mixin
  },
  tick: function() {
    this.setState({seconds: this.state.seconds + 1});
  },
  render: function() {
    return (
      <p>
        React has been running for {this.state.seconds} seconds.
      </p>
    );
  }
});

ReactDOM.render(
  <TickTock />,
  document.getElementById(‘example‘)
);
View Code

  If a component is using multiple mixins and several mixins define the same lifecycle method, all of the lifecycle methods are guaranteed to be called.   Methods defined on mixins run in the order mixins were listed, followed by a method call on the component.

  Mixins已经被证明坑太多,当你需要重用组件时,优先考虑HOC。

参考:https://facebook.github.io/react/docs/react-without-es6.html#mixins

React Mixins

标签:tin   ever   define   mixin   get   initial   har   target   https   

原文地址:http://www.cnblogs.com/tekkaman/p/7421085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!