| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <script src="./babel.min.js"></script>
- <script src="./react.development.js"></script>
- <script src="./react-dom.development.js"></script>
- </head>
- <body>
- <div id="root"></div>
- <script type="text/babel">
- /**
- * 页面展示当前时间
- * 第一个按钮 点击停止
- * 第二个按钮 点击继续
- */
- function Clock() {
- return <Child />
- }
- class Child extends React.Component {
- constructor() {
- super();
- this.state = {
- now: new Date().toLocaleTimeString()
- }
- this.handleClick = this.handleClick.bind(this);
- this.handleStop = this.handleStop.bind(this);
- this.timer = null;
- }
- getTime() {
- this.timer = setInterval(() => {
- this.setState({
- now: new Date().toLocaleTimeString()
- })
- }, 1000)
- }
- componentDidMount() {
- this.getTime();
- }
- componentDidUpdate() {
- console.log(this.state.now)
- }
- handleStop() {
- clearInterval(this.timer)
- }
- handleClick() {
- this.getTime()
- }
- componentWillUnmount() {
- clearInterval(this.timer)
- }
- render() {
- return (
- <div>
- <h1>{this.state.now}</h1>
- <button onClick={this.handleClick}>继续</button>
- <button onClick={this.handleStop}>暂停</button>
- </div>
- )
- }
- }
- const element = <Clock />
- const container = document.getElementById("root");
- const root = ReactDOM.createRoot(container)
- root.render(element);
- </script>
- </body>
- </html>
|