Tekkaman

导航

 

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

posted on 2017-08-24 01:35  Tekkaman  阅读(230)  评论(0编辑  收藏  举报