react.js 父子組件數(shù)據(jù)綁定實(shí)時(shí)通訊的示例代碼
更新時(shí)間:2017年09月25日 11:44:53 作者:八bug哥哥
本篇文章主要介紹了react.js 父子組件數(shù)據(jù)綁定實(shí)時(shí)通訊的示例代碼,
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)屬性對(duì)象
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)用多次會(huì)合并,只執(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React報(bào)錯(cuò)信息之Expected?an?assignment?or?function?call?and?
這篇文章主要介紹了React報(bào)錯(cuò)之Expected?an?assignment?or?function?call?and?instead?saw?an?expression,下面有兩個(gè)示例來展示錯(cuò)誤是如何產(chǎn)生的,需要的朋友可以參考下2022-08-08
一文詳解ReactNative狀態(tài)管理rematch使用
這篇文章主要為大家介紹了ReactNative狀態(tài)管理rematch使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

