声明:将以一个钟表组件作为例子
class MtkClock {
constructor(){
this.data = this.dataInit
this.methods = {
tick: this.tick
}
this.mounted = this.componentDidMount
this.beforeDestroy = this.componentWillUnmount
this.render = this.render_vue
}
dataInit(){
return {
date: new Date(),
timer: null,
}
}
tick() {
this.date = new Date()
}
componentDidMount(){
this.timer = setInterval(() => this.tick(), 1000)
}
componentWillUnmount(){
clearInterval(this.timer);
}
render_vue(){
return (
<p>{this.date.toLocaleTimeString()}</p>
)
}
}
import React from 'react';
class MtkClock extends React.Component{
constructor(props){
super(props)
this.state = this.dataInit()
}
dataInit(){
return {
date: new Date(),
timer: null,
}
}
tick() {
this.setState(() =>{return {date : new Date()};});
}
componentDidMount(){
this.timer = setInterval(() => this.tick(), 1000)
}
componentWillUnmount(){
clearInterval(this.timer);
}
render(){
return (
<p>{this.state.date.toLocaleTimeString()}</p>
)
}
}
注意:
(1) React会将以小写字母开头的组件视为原生 DOM 标签,故组件名称必须以大写字母开头
参考文档:
网友评论