React中的props和state

props意为属性,只可父组件改变子组件的props,而子组件不能自更新,props是子组件暴露给外部的公有接口

state意为状态,所谓的状态就是一种标记,设计用来控制某种逻辑,类似于后台语言中的flag,全局的私有变量,外部不能访问,state的改变会被render()函数自动捕捉到,当然state改变后是否执行render,还取决于bool shouldComponentUpdate(nextProps, nextState) 返回false则不会重新渲染。

改变state的方法,setState({
……
})
不能直接给state重新赋值

那么问题来了 ,外部只能控制props,怎么让子组件捕捉到props发生改变了呢?
void componentWillReceiveProps(nextProps)
nextProps即为新值,外部想传入的值!如此,子组件就获取了外界传来的参数。

父组件 ClockApp

import React, { Component } from 'react'
import Clock from "./Clock"

export default class ClockApp extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isRun: true,
            isShow: true
        }
    }

    onValueChange(event){
        if(event.target.name==="run") this.setState({
            isRun:!this.state.isRun
        })
        else if(event.target.name==="show") this.setState({
            isShow:!this.state.isShow
        })
    }
    render() {
        return (
            <div>

                <input type="checkbox" onChange={this.onValueChange.bind(this)} name="run"/><span>{this.state.isRun?"开启":"停止"}</span><br/>
                <input type="checkbox" onChange={this.onValueChange.bind(this)} name="show"/><span>{this.state.isShow?"显示":"隐藏"}</span><br/>
                <Clock isShow={this.state.isShow}  isRun={this.state.isRun}/>
            </div>

        );
    }


}

子组件Clock

import React, { Component } from "react"

export default class Clock extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: new Date()
        };
    }

    componentWillMount () {
        this.timer = setInterval(() => {
          this.setState({ date: new Date() })
        }, 1000)
      }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    componentWillReceiveProps(nextProps){
        if(nextProps.isRun){
            clearInterval(this.timer);
            this.timer = setInterval(() => {
                this.setState({ date: new Date() })
            }, 1000)
        }
        else
            clearInterval(this.timer);
    }


    render() {       
        var rStyle = {
            display:this.props.isShow?"block":"none"
        };
        return (
            <div style={rStyle}>
                <h2>现在时间</h2>
                <span >{this.state.date.toLocaleTimeString()}</span>
            </div>
        );
    }

}

简陋的界面

这里写图片描述

控制时钟启动、暂停、显示、隐藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值