码迷,mamicode.com
首页 > 其他好文 > 详细

react-当前的时:分:秒-每秒更新

时间:2019-11-15 20:25:11      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:时间   --   com   es6   stat   timer   doctype   实现   方法   

实现效果:

技术图片

<!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>

 

 

 

 

 

react-当前的时:分:秒-每秒更新

标签:时间   --   com   es6   stat   timer   doctype   实现   方法   

原文地址:https://www.cnblogs.com/yi-miao-2333/p/11869178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!