Mixin用于定于复用方法,并在其他Component中使用
var SetIntervalMixin = { componentWillMount: function() { //生命周期开始回调 this.intervals = []; }, setInterval: function() { //自定义公用方法 this.intervals.push(setInterval.apply(null, arguments)); }, componentWillUnmount: function() { //生命周期结束回调 this.intervals.forEach(clearInterval); } }; var TickTock = React.createClass({ mixins: [SetIntervalMixin], //启用mixin中的公共方法 getInitialState: function() { return {seconds: 0}; }, componentDidMount: function() { this.setInterval(this.tick, 1000); //调用mixin中的setInterval方法 }, tick: function() { this.setState({seconds: this.state.seconds + 1}); }, render: function() { return ( <p> React has been running for {this.state.seconds} seconds. </p> ); } }); ReactDOM.render( <TickTock />, document.getElementById(‘example‘) );
注:Mixin中的方法不应对DOM及state有任何操作!
时间: 2024-10-11 05:45:26