0
点赞
收藏
分享

微信扫一扫

react 开始 三 state

alanwhy 2023-02-09 阅读 72


class A extends React.Component
{
constructor(props)
{
super(props)
this.state={//靠这个state对象 可以实现值的变化
date:new Date()
}
}
componentDidMount() {//挂载 组件第一次加到DOM时
this.timerID = setInterval(//整个计时器 修改date
() => this.tick(),
1000
);
}

componentWillUnmount() {//卸载
clearInterval(this.timerID);
}

tick() {//state要用React的setState函数来更新才行
this.setState({
date: new Date()
});
}
render()
{
return (
<div>
{this.state.date.toLocaleTimeString()}
</div>
)
}
}

ReactDOM.render(
<div>
<A />
</div>
,
document.getElementById('example')//
);

 

举报

相关推荐

0 条评论