react.js我自己還在摸索學(xué)習(xí)中,碰到父子組件數(shù)據(jù)綁定實(shí)時(shí)通訊的問題,研究了一下,分享給大家,也給自己留個(gè)筆記:
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> ) }}/** 大家默認(rèn)規(guī)定的一些步驟,方便大家看* 1.默認(rèn)值* 2.初始化狀態(tài)* 3.鉤子函數(shù)* 4.方法函數(shù)* */class Counter extends Component{ //默認(rèn)屬性對象 static defaultProps={ number:5 } constructor(props){ super(props); //獲取我的初始狀態(tài) this.state={ number:props.number } } //鉤子函數(shù) componentWillMount(){ console.log('組件將要掛載') } componentDidMount(){ console.log("組件掛載完成") } handleClick=()=>{ //this.setState方法是異步的,一個(gè)函數(shù)里面只能調(diào)用一次this.setState方法 //調(diào)用多次會合并,只執(zhí)行一次 this.setState((prev,next)=>({ //上一次的狀態(tài)prev number:prev.number+1 }),()=>{ console.log("回調(diào)函數(shù)執(zhí)行") }) // this.setState({index:this.state.index+1}) } render(){ //調(diào)用子組件ChildCounter,把當(dāng)前狀態(tài)值傳過去 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"))以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答