Bootstrap

react组件间通信的三种方式

1.父组件向子组件传值

state:传递数据
props:接收数据

//父组件
class Parent extends React.Component {
  state = {
    lastName: 'Tom'
  }

  render(){
    return(
      <div className="parent">
        父组件:
        <Child name={this.state.lastName}/>
      </div>
    )
  }
}

//子组件
const Child = (props) => {
  return (
    <div className="child">
      <p>子组件:接收到父组件的数据:{props.name}</p>
    </div>
  )
}

ReactDOM.render(<Parent/>,document.getElementById('root'))

2.子组件向父组件传值

//父组件
class Parent extends React.Component {
  state = {
    parentMsg: ''
  }
//提供回调函数,用来接收数据
getChildMsg = (data) =>{
  console.log('接收到子组件中传递过来的数据',data)

  this.setState({
    parentMsg: data
  })
}
  render(){
    return(
      <div className="parent">
        父组件:{this.state.parentMsg}
        <Child getMsg={this.getChildMsg}/>
      </div>
    )
  }
}

//子组件
class Child extends React.Component {
  state = {
    msg:'敲代码'
  }
  handelCilck = () => {
    //子组件调用父组件中传递过来的数据
    this.props.getMsg(this.state.msg);
  }

  render() {
    return (
      <div className="child">
        子组件:<button onClick={this.handelCilck}>点击,给父组件传递数据</button>
      </div>
    )
  }
}
ReactDOM.render(<Parent/>,document.getElementById('root'))

3.兄弟组件

状态提升思想

//父组件
class Counter extends React.Component {
  //提供共享状态
  state = {
    count: 0
  }
  //提供修改状态的方法
  onIncrement = ()=>{
    this.setState({count: this.state.count + 1});
  }
  render() {
    return (
      <div>
        <Child1 count={this.state.count}/>
        <Child2 onIncrement={this.onIncrement}/>
      </div>
    )
  }
}

const Child1 = (props) => {
  return (
    <h1>计数器:{props.count}</h1>
  )
}

const Child2 = (props) => {
  return (
    <button onClick={() => {props.onIncrement()}}>+1</button>
  )
}

ReactDOM.render(<Counter/>,document.getElementById('root'))
;