react系列(9)混合mixins

来源:互联网 发布:淘宝代写代码靠谱不 编辑:程序博客网 时间:2024/05/29 06:56

混合是指定义一个对象,让组件去继承该对象的方法和状态的过程,该对象也被称为混合对象。若组件和被继承的混合对象具体相同的生命钩子函数将要被执行,则混合对象的函数会优先执行,然后再到组件内相同函数执行,但仅限于生命钩子函数。

另外,组件内不允许有和混合对象相同命名的方法(非生命钩子函数),如例子中的handlAction,否则会报错。ReactClassInterface: You are attempting to define `handlAction` on your component more than once. This conflict may be due to a mixin.

// 混合var mixinCommon = {componentWillMount: function() {console.log("mix componentWillMount!"); //优先执行},handlAction:function(){console.log("mix action!"); //该方法不允许再从组件中重构,否则会报错}}var HelloWorld = React.createClass({mixins:[mixinCommon],componentWillMount: function() {console.log("HelloWorld componentWillMount!"); //仍会执行},componentDidMount: function() {      this.handlAction(); //调用mixinCommon的方法    },    render: function() {      return <h1>Hello World!</h1>;    }});ReactDOM.render(<HelloWorld />,document.getElementById("example"));

运行结果: