react.js 父子组件数据绑定实时通讯

本文介绍了一个使用React实现的基本计数器应用。该应用通过按钮点击来增加计数器数值,并将当前计数显示在页面上。此外,还演示了如何通过子组件传递状态值,以及如何使用React生命周期方法。
import React,{Component} from 'react'
import ReactDOM from 'react-dom'

class ChildCounter extends Component{
    render(){
        return(
            <div style={{border:'1px solid red'}}>
                {this.props.count}
            </div>
        )
    }
}
/*
* 大家默认规定的一些步骤,方便大家看
* 1.默认值
* 2.初始化状态
* 3.钩子函数
* 4.方法函数
* */
class Counter extends Component{
    //默认属性对象
    static defaultProps={
        number:5
    }
    constructor(props){
        super(props);
        //获取我的初始状态
        this.state={
            number:props.number
        }
    }
    //钩子函数
    componentWillMount(){
        console.log('组件将要挂载')
    }

    componentDidMount(){
        console.log("组件挂载完成")
    }

    handleClick=()=>{
        //this.setState方法是异步的,一个函数里面只能调用一次this.setState方法
        //调用多次会合并,只执行一次
        this.setState((prev,next)=>({
            //上一次的状态prev
            number:prev.number+1
        }),()=>{
            console.log("回调函数执行")
        })

        // this.setState({index:this.state.index+1})

    }
    render(){
        //调用子组件ChildCounter,把当前状态值传过去
        return(
            <div>
                <p>{this.state.number}</p>
                <button onClick={this.handleClick}>+</button>
                <ChildCounter count={this.state.number}></ChildCounter>
            </div>
        )
    }
}
//渲染到页面
ReactDOM.render(<Counter></Counter>,document.querySelector("#root"))

 

转载于:https://www.cnblogs.com/null11/p/7581565.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值