实现效果:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <!-- Don't use this in production: --> <!--转码--> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <div id="root"></div> </body> </html> <script type="text/babel"> //创建一个ES6class,并且继承于React..Component class Clock extends React.Component{ //添加一个class构造函数 constructor(props){ super(props); this.state = {date:new Date()}; } //挂载 componentDidMount(){ this.timerID = setInterval( () =>this.tick(), 1000 ); } //卸载 componentWillUnmount(){ clearInterval(this.timerID); } //Clock每秒调用这个方法,更新setState tick(){ this.setState({ date: new Date() }); } //添加一个空的render()方法 render(){ //将函数移动到render()方法中,this.props替换props return( <div> <h2>当前时间:{this.state.date.toLocaleTimeString()}</h2> </div> ); } } //渲染 ReactDOM.render( <Clock />, document.getElementById('root') ); </script>