mixin模式就是一些提供能够被一个或者一组子类简单继承功能的类,意在重用其功能。在面向对象的语言中,我们会通过接口继承的方式来实现功能的复用。但是在javascript中,我们没办法通过接口继承的方式,但是我们可以通过javascript特有的原型链属性,将功能引用复制到原型链上,达到功能的注入。
在React官网中有一个定时器的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script>
<script src="http://static.runoob.com/assets/react/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const Timer = React.createClass({
getInitialState: function () {
return {secondsElapsed: 0};
},
tick: function () {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function () {
this.interval = setInterval(this.tick, 1000);
},
componentWillMount: function () {
clearInterval(this.interval);
},
render() {
return (<div>Seconds Elapsed: {this.state.secondsElapsed}</div>)
}
});
ReactDOM.render(
<div>
<Timer />
</div>,
document.getElementById('root')
);
</script>
</body>
</html>
在这里,我们定义了一个定时器,但是如果我们想要在多个地方同时使用这个定时器,我们就可以用上mixin这个神器,具体怎么用呢?废话不多说,上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script>
<script src="http://static.runoob.com/assets/react/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const IntervalMixin = {
setInterval: function (callback, interval) {
const token = setInterval(callback, interval);
this._intervals.push(token);
return token;
},
componentDidMount: function () {
this._intervals = [];
},
componentWillUnmount: function () {
this._intervals.map(clearInterval);
}
};
const Since2018 = React.createClass({
mixins: [IntervalMixin],
componentDidMount: function () {
this.setInterval(this.forceUpdate.bind(this), 1000);
},
render: function () {
const from = Number(new Date(2018, 11, 14));
const to = Date.now();
return (
<div>{Math.round((to-from)/1000)}</div>
)
}
});
ReactDOM.render(
<div>
<Since2018 />
</div>,
document.getElementById('root')
);
</script>
</body>
</html>
用这个方法,我们可以很轻松的得到,从2018年12月14日到现在过了多少秒了。