react.js 父子組件數據綁定實時通信

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"))
相關文章
相關標籤/搜索