如果不使用 ES6 的 Class,则可以考虑用 create-react-class 。
var HelloCreateClass = createReactClass({
render: function() {
return <h1>Hello, {this.props.greeting}</h1>;
}
});
以下改写 Class Component <Clock>
的例子:
var Clock = createReactClass({
getInitialState: function() { //设定 State
return {
date: new Date(),
timerID: ''
};
},
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
},
componentWillUnmount() {
clearInterval(this.timerID);
},
tick() {
this.setState({
date: new Date()
});
},
start() { //不需要写 this.start = this.start.bind(this) 就自动绑定
this.timerID = setInterval(
() => this.tick(),
1000
);
},
stop() {
clearInterval(this.timerID);
},
render: function() {
return <div>
<h1>Hello, Create Class!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<button onClick={this.start}> Start</button><button onClick={this.stop}> Stop</button>
</div>;
}
});
ES6 并没有支援任何 mixin 语法。因此当你在 React 中使用 ES6 class 时也不支援使用 mixin。
我们也发现在程序中使用 mixin 会造成很多问题,因此不建议在新的程序码中使用 mixin。
此段落内容仅供参考。 - React Document
下面将 setinterval 相关功能拆出 Mixin 的功能作为例子:
var SetIntervalMixin = {
getInitialState: function() { //设定 State
return {
date: new Date(),
timerID: ''
};
},
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
},
componentWillUnmount() {
clearInterval(this.timerID);
},
tick() {
this.setState({
date: new Date()
});
},
};
var Clock = createReactClass({
mixins: [SetIntervalMixin], // 使用 mixin
//略
});
以上今天。
参考资料:
https://zh-hant.reactjs.org/docs/react-without-es6.html
https://zh-hant.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html
<<: Day 27 -资料库应用小程序 首页功能(内涵程序码)
今天谈一下即时作业系统(Real-time operating system, RTOS),根据维基...
简介- 为什麽要使用阵列? 当我们想要宣告一个变数的时候,我们可以一次叫一个 像是这样 #inclu...
今天来把专案上到GitHub啦~ 老实说Git就是那种学校没教,但是你工作又90%会用到的重要东东 ...
运算子(Operator) 在程序码中代表运算的符号,参与运算的数值或变数称为运算元(Operand...
前言 参考文件 https://kubernetes.io/docs/tutorials/state...