首頁  >  文章  >  web前端  >  react.js 父子元件資料綁定即時通訊實例展示

react.js 父子元件資料綁定即時通訊實例展示

巴扎黑
巴扎黑原創
2017-09-26 09:35:251629瀏覽

本篇文章主要介紹了react.js 父子元件資料綁定即時通訊的範例程式碼,

react.js我自己還在摸索學習中,碰到父子元件資料綁定即時通訊的問題,研究了一下,分享給大家,也給自己留個筆記:


import React,{Component} from 'react'
import ReactDOM from 'react-dom'

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

  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(
      <p>
        <p>{this.state.number}</p>
        <button onClick={this.handleClick}>+</button>
        <ChildCounter count={this.state.number}></ChildCounter>
      </p>
    )
  }
}
//渲染到页面
ReactDOM.render(<Counter></Counter>,document.querySelector("#root")

以上是react.js 父子元件資料綁定即時通訊實例展示的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn