react mixins编写

react

var LogMixin = {

componentWillMount: function () {

console.log('Component will mount');

},

componentDidMount: function () {

console.log('Component did mount');

}

};

var AComponent = React.createClass({

mixins: [LogMixin],

render: function () {

return (

<div>AComponent</div>

)

}

});

var BComponent = React.createClass({

mixins: [LogMixin],

render: function () {

return (

<div>BComponent</div>

)

}

});

mixins的详细学习:https://segmentfault.com/a/1190000002704788

Mixins

利用React的Mixins,编写的代码就像这样的:

var LogMixin = {

componentWillMount: function () {

console.log('Component will mount');

},

componentDidMount: function () {

console.log('Component did mount');

}

};

var AComponent = React.createClass({

mixins: [LogMixin],

render: function () {

return (

<div>AComponent</div>

)

}

});

var BComponent = React.createClass({

mixins: [LogMixin],

render: function () {

return (

<div>BComponent</div>

)

}

});

Mixins有点类似AOP。所谓的mixins就是将组件里的方法抽出来。实际上Mixins里的this是指向组件的,使用了Mixins以后,组件也可以调用Mixins里的方法。

组件调用Mixins方法

var Mixin = {

log:function(){

console.log('Mixin log');

}

};

var Component = React.createClass({

mixins: [Mixin],

componentWillMount: function () {

this.log();

},

render: function () {

return (

<div>Component</div>

)

}

});

控制台打印:

$ Mixin log

生命周期方法

Mixins里也可以编写组件生命周期的方法,需要注意的是:Mixins里的方法并不会覆盖组件的生命周期方法,会在先于组件生命周期方法执行。

var Mixin = {

componentWillMount: function () {

console.log('Mixin Will Mount');

}

};

var Component = React.createClass({

mixins: [Mixin],

componentWillMount: function () {

console.log('Component Will Mount');

},

render: function () {

return (

<div>Component</div>

)

}

});

控制台打印:

$ Mixin Will Mount

$ Component Will Mount

使用多个Mixin

组件也可以使用多个Mixin

var AMixin = {

componentWillMount: function () {

console.log('AMixin Will Mount');

}

};

var BMixin = {

componentWillMount: function () {

console.log('BMixin Will Mount');

}

};

var Component = React.createClass({

mixins: [AMixin,BMixin],

componentWillMount: function () {

console.log('Component Will Mount');

},

render: function () {

return (

<div>Component</div>

)

}

});

控制台打印:

$ AMixin Will Mount

$ BMixin Will Mount

$ Component Will Mount

数组引入的顺序,决定了Mxins里生命周期方法的执行顺序。

不允许重复

除了生命周期方法可以重复以外,其他的方法都不可以重复,否则会报错

情景1

var AMixin = {

log: function () {

console.log('AMixin Log');

}

};

var BMixin = {

log: function () {

console.log('BMixin Log');

}

};

var Component = React.createClass({

mixins: [AMixin,BMixin],

render: function () {

return (

<div>Component</div>

)

}

});

情景2

var Mixin = {

log: function () {

console.log('Mixin Log');

}

};

var Component = React.createClass({

mixins: [Mixin],

log:function(){

console.log('Component Log');

},

render: function () {

return (

<div>Component</div>

)

}

});

以上两种情景,都会报错,控制信息如下,所以使用的时候要小心了

 

以上是 react mixins编写 的全部内容, 来源链接: utcz.com/z/383006.html

回到顶部