react.js 父子组件数据绑定实时通讯的示例代码

在希望的田野上,我们看到了希望,看到了未来,看到了祖国未来繁荣昌盛的景象。

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"))

以上就是react.js 父子组件数据绑定实时通讯的示例代码。逃避不一定躲得过,面对不一定难受.转身不一定最软弱.更多关于react.js 父子组件数据绑定实时通讯的示例代码请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
react axios 跨域访问一个或多个域名问题

React+ajax+java实现上传图片并预览功能

React组件对子组件children进行加强的方法

在React中写一个Animation组件为组件进入和离开加上动画/过度效果

回顾Javascript React基础