首页 > 其他 > 详细

React Mixins

时间:2017-08-24 09:40:14      阅读:351      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!