组件的原则就是模块化,彼此之间相互独立,但是有时候不同的组件之间可能会共用一些功能,共享一部分代码。所以 React 提供了 mixins 这种方式来处理这种问题。
Mixin 就是用来定义一些方法,使用这个 mixin 的组件能够自由的使用这些方法(就像在组件中定义的一样),所以 mixin 相当于组件的一个扩展,在 mixin 中也能定义“生命周期”方法。
var DefaultNameMixin = {
getDefaultProps: function () {
return {
name: "Skippy",
food: "Pancakes"
};
}
};
var ComponentOne = React.createClass({
mixins: [DefaultNameMixin],
render: function () {
return (
<div>
<h4>{this.props.name}</h4>
<p>Favorite food: {this.props.food}</p>
</div>
) ;
}
});
ReactDOM.render(<ComponentOne/>, document.body);
Mixin定义的一些功能都是可以共享,如果当我们使用相同状态和属性时将会报错。
var DefaultNameMixin = {
getDefaultProps: function () {
return {name: "Skippy"};
}
};
var ComponentTwo = React.createClass({
mixins: [DefaultNameMixin],
getDefaultProps: function () {
return {
food: "Pancakes",
name: "Lizy"
};
},
render: function () {
return (
<div>
<h4>{this.props.name}</h4>
<p>Favorite food: {this.props.food}</p>
</div>
);
}
});
ReactDOM.render(<ComponentTwo/>, document.body);
console.log:
Uncaught Error: Invariant Violation: mergeObjectsWithNoDuplicateKeys(): Tried to merge two objects with the same key: name
当我们的component和mixin都含有生命周期方法时,我们的mixin方法始终会先执行.
var LogOnMountMixin = {
componentDidMount: function () {
console.log("mixin mount method");
}
};
var ComponentOne = React.createClass({
mixins: [LogOnMountMixin],
componentDidMount: function () {
mixin mount method component one mount method
console.log("component one mount method"); }, render: function() { return <h2>Hello {this.props.name}</h2>; } }); ReactDOM.render(<ComponentOne/>, document.body);
console.log:
mixin mount method component one mount method
当我们include多个mixin时,他们会从左到右执行.
var LogOnMountMixin = {
componentDidMount: function () {
console.log("mixin mount method");
}
};
var MoreLogOnMountMixin = {
componentDidMount: function () {
console.log("another mixin mount method");
}
};
var ComponentOne = React.createClass({
mixins: [MoreLogOnMountMixin, LogOnMountMixin],
componentDidMount: function () {
console.log("component one mount method");
},
...
var ComponentTwo = React.createClass({
mixins: [LogOnMountMixin, MoreLogOnMountMixin],
componentDidMount: function () {
console.log("component two mount method");
},
console.log:
another mixin mount method mixin mount method component one mount method mixin mount method another mixin mount method component two mount method
本文深入解析了React中混入(Mixin)的概念及其应用,通过实例展示了如何利用混入来扩展组件的功能,包括如何共享方法、生命周期方法的调用顺序以及在组件中包含多个混入的情况下的行为。
2169

被折叠的 条评论
为什么被折叠?



