React生命周期函数使用实例--时钟组件

思路:
React生命周期:挂载、更新、卸载

挂载:

构造函数constructor(props): 在初始化状态,绑定函数时使用构造函数
super(props); 必须是构造函数的第一句
this.state:定义状态机
为隐藏时间的button按钮绑定当前组件
渲染函数render(): 是class组件中唯一必须实现的方法
挂载函数componentDidMount(): 在函数中完成订阅

卸载:
componentWillUnmount()卸载函数: 清空定时器

<body>
    <div id="demo-7"></div>
    <script type="text/babel">
        //Clock组件
        class Clock extends React.Component {
            constructor(props) {  //构造函数
                //初始化状态,绑定函数使用构造函数
                super(props);  //必须是构造函数的第一句,super代表当前组件的父类
                this.state = { // 状态机
                    date: new Date(),
                    show: true,
                    text: "隐藏"
                }
                //为handleClickShow事件绑定当前组件Clock
                this.handleClickShow = this.handleClickShow.bind(this);
            }
            //渲染函数,是class组件中唯一必须实现的方法
            render() {
                let isShow = this.state.show;
                let element;
                if (isShow) {//如果state中的show为true
                    //显示state的date,将date转化成本地时间类型的字符串
                    element = <h2 className="h2">{ this.state.date.toLocaleTimeString() }</h2>
                } else {
                    element = null;
                }
                return (
                    //返回React元素
                    <div>
                        <button onClick={this.handleClickShow}>{this.state.text}计时器</button>
                        {element}
                    </div>
                )
            }
            componentDidMount() { //挂载函数
                //每秒钟执行一次时钟函数
                this.timerID = setInterval(
                    () => this.tick(),
                    1000
                )
            }
 
            tick(){ //时钟函数
                this.setState({ // setState用于更新组件的state
                    date: new Date()
                });
            }
 
            //事件响应函数
            handleClickShow() {
                this.setState(state => ({
                    show: !state.show,
                    text: !state.show ? "隐藏" : "显示"//取反为真则隐藏,取反为假则显示
                })) 
            }
            //卸载组件(清除定时器)
            componentWillUnmount() {
                clearInterval(this.timerID);
            }
        }
        ReactDOM.render(
            <Clock />,
            document.getElementById("demo-7")
        )
    </script>
</body>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值