请使用高阶组件而不是Mixin
简单的例子
// 使用mixin
var WithLink = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function () {
return {message: 'Hello!'};
},
render: function () {
return <input type="text" valueLink={this.linkState('message')}/>;
}
});
// 使用高阶组件的做法
var WithLink = React.createClass({
getInitialState: function () {
return {message: 'Hello!'};
},
render: function () {
return <input type="text" valueLink={LinkState(this,'message')}/>;
}
});
更加详细的例子
// 使用Mixin Mixin
var CarDataMixin = {
componentDidMount: {
// fetch car data and
// call this.setState({carData: fetchedData}),
// once data has been (asynchronously) fetched
}
};
var FirstView = React.createClass({
mixins: [CarDataMixin],
render: function () {
return (
<div>
<AvgSellingPricesByYear country="US" dataset={this.state.carData}/>
<AvgSellingPricesByYear country="UK" dataset={this.state.carData}/>
<AvgSellingPricesByYear country="FI" dataset={this.state.carData}/>
</div>
)
}
});
// 使用高阶组件
var bindToCarData = function (Component) {
return React.createClass({
componentDidMount: {
// fetch car data and
// call this.setState({carData: fetchedData}),
// once data has been (asynchronously) fetched
},
render: function () {
return <Component carData={ this.state.carData }/>
}
});
};
// 将你的组件使用高阶组件包裹起来
var FirstView = bindToCarData(React.createClass({
render: function () {
return (
<div>
<AvgSellingPricesByYear country="US" dataset={this.props.carData}/>
<AvgSellingPricesByYear country="UK" dataset={this.props.carData}/>
<AvgSellingPricesByYear country="FI" dataset={this.props.carData}/>
</div>
)
}
}));
参考资料:
- Mixins are dead - Long live higher ordercomponents
- Mixins are considered harmful
- Stackoverflow: Using mixins vs components for code reuse
- Stackoverflow: Composition instead of mixins in React
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「IT平头哥联盟」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程