14.Clock.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="./babel.min.js"></script>
  8. <script src="./react.development.js"></script>
  9. <script src="./react-dom.development.js"></script>
  10. </head>
  11. <body>
  12. <div id="root"></div>
  13. <script type="text/babel">
  14. /**
  15. * 页面展示当前时间
  16. * 第一个按钮 点击停止
  17. * 第二个按钮 点击继续
  18. */
  19. function Clock() {
  20. return <Child />
  21. }
  22. class Child extends React.Component {
  23. constructor() {
  24. super();
  25. this.state = {
  26. now: new Date().toLocaleTimeString()
  27. }
  28. this.handleClick = this.handleClick.bind(this);
  29. this.handleStop = this.handleStop.bind(this);
  30. this.timer = null;
  31. }
  32. getTime() {
  33. this.timer = setInterval(() => {
  34. this.setState({
  35. now: new Date().toLocaleTimeString()
  36. })
  37. }, 1000)
  38. }
  39. componentDidMount() {
  40. this.getTime();
  41. }
  42. componentDidUpdate() {
  43. console.log(this.state.now)
  44. }
  45. handleStop() {
  46. clearInterval(this.timer)
  47. }
  48. handleClick() {
  49. this.getTime()
  50. }
  51. componentWillUnmount() {
  52. clearInterval(this.timer)
  53. }
  54. render() {
  55. return (
  56. <div>
  57. <h1>{this.state.now}</h1>
  58. <button onClick={this.handleClick}>继续</button>
  59. <button onClick={this.handleStop}>暂停</button>
  60. </div>
  61. )
  62. }
  63. }
  64. const element = <Clock />
  65. const container = document.getElementById("root");
  66. const root = ReactDOM.createRoot(container)
  67. root.render(element);
  68. </script>
  69. </body>
  70. </html>