Home > Web Front-end > JS Tutorial > Detailed example of react.js parent-child component data binding real-time communication

Detailed example of react.js parent-child component data binding real-time communication

小云云
Release: 2018-02-01 13:15:33
Original
2113 people have browsed it

This article mainly introduces to you the sample code of react.js parent-child component data binding real-time communication. I am still learning react.js myself. I encountered the problem of parent-child component data binding real-time communication. I studied it and shared it. For everyone, and also leave a note for yourself:


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"))
Copy after login

Related recommendations:

Vue2.0 parent-child component delivery Detailed explanation of functions

Detailed explanation of event bus non-parent-child component communication in vue

React high-order component instance analysis

The above is the detailed content of Detailed example of react.js parent-child component data binding real-time communication. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template