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"))以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答