|
|
@@ -18,7 +18,53 @@
|
|
|
* 第一个按钮 点击停止
|
|
|
* 第二个按钮 点击继续
|
|
|
*/
|
|
|
- const element = <h1>你好</h1>
|
|
|
+ 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);
|