實現效果:html
<!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>