1.mixin的作用是抽离公共功能,不存在渲染dom的需要,所以它没有render方法。如果你定义了render方法,那么他会和组件的render方法冲突而报错。
2.mixin不应该污染state,所以他也没有 setState 方法。
3.mixin应该只提供接口(即方法),不应该提供任何属性。
TimerMixin
- var TimerMixin = function() {
- return {
- componentDidMount: function() {
- this._interval = setInterval(this._onTick, 1000);
- },
- format: function(d) {
- return d >= 10 ? d : ("0"+d);
- },
- _onTick: function() {
- var d = new Date();
- this.timerTick(this.format(d.getHours()) + ":" + this.format(d.getMinutes()) + ":" + this.format(d.getSeconds()));
- },
- componentWillUnmount: function() {
- clearInterval(this._interval);
- }
- }
- }
- var Card = React.createClass({
- mixins: [
- TimerMixin()
- ],
- timerTick: function(t) {
- this.setState({
- time: t
- });
- },
- getInitialState: function() {
- return {
- time: 'loading time'
- }
- },
- render: function() {
- return (
- <div>Hello {this.props.name}! It is {this.state.time} !</div>
- );
- }
- });

本文介绍了React中Mixins的概念及使用方法,强调Mixins用于抽离公共功能,并通过实例展示了如何利用Mixins实现定时更新时间的功能。
1552

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



