欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-28 23:34:32
react.js我自己还在摸索学习中,碰到父子组件数据绑定实时通讯的问题,研究了一下,分享给大家,也给自己留个笔记: import react,{compon...

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。