思路:
React生命周期:挂载、更新、卸载
挂载:
构造函数constructor(props):
在初始化状态,绑定函数时使用构造函数
super(props); 必须是构造函数的第一句
this.state:定义状态机
为隐藏时间的button按钮绑定当前组件
渲染函数render():
是class组件中唯一必须实现的方法
挂载函数componentDidMount():
在函数中完成订阅
卸载:
componentWillUnmount()卸载函数:
清空定时器
<body>
<div id="demo-7"></div>
<script type="text/babel">
//Clock组件
class Clock extends React.Component {
constructor(props) { //构造函数
//初始化状态,绑定函数使用构造函数
super(props); //必须是构造函数的第一句,super代表当前组件的父类
this.state = { // 状态机
date: new Date(),
show: true,
text: "隐藏"
}
//为handleClickShow事件绑定当前组件Clock
this.handleClickShow = this.handleClickShow.bind(this);
}
//渲染函数,是class组件中唯一必须实现的方法
render() {
let isShow = this.state.show;
let element;
if (isShow) {//如果state中的show为true
//显示state的date,将date转化成本地时间类型的字符串
element = <h2 className="h2">{ this.state.date.toLocaleTimeString() }</h2>
} else {
element = null;
}
return (
//返回React元素
<div>
<button onClick={this.handleClickShow}>{this.state.text}计时器</button>
{element}
</div>
)
}
componentDidMount() { //挂载函数
//每秒钟执行一次时钟函数
this.timerID = setInterval(
() => this.tick(),
1000
)
}
tick(){ //时钟函数
this.setState({ // setState用于更新组件的state
date: new Date()
});
}
//事件响应函数
handleClickShow() {
this.setState(state => ({
show: !state.show,
text: !state.show ? "隐藏" : "显示"//取反为真则隐藏,取反为假则显示
}))
}
//卸载组件(清除定时器)
componentWillUnmount() {
clearInterval(this.timerID);
}
}
ReactDOM.render(
<Clock />,
document.getElementById("demo-7")
)
</script>
</body>