react组件通信

组件传值

state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。
这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。

父传子

属性传值

  • 子组件定义接受数据属性名称
  • 父组件向该属性赋值

//父组件
class  Father extends React.Component {
  constructor() {
    super();
    this.state = {
      属性名称:属性值
    }
  }

  render(){
    return({
      <子组件 子组件属性名称={this.state.属性名称}/>
    });
  }
}

//子组件接受
class Son extends React.Component{
  constructor(props){
    super();
    this.state = props;
  }

  render(){
    return(
      <子元素标签>{this.state.子组件属性名称}</子元素标签>
    );
  }

}

子传父

回调函数方式

//父组件
class  Father extends React.Component {
  constructor() {
    super();
    this.state = {
      属性名称:属性值
    }
  }

  // 父组件接受数据定于函数
  getData = (需要传递给父组件的值)=>{
    //拿到子组件传递给父组件的值
  }

  render(){
    return({
      <子组件 子组件属性名称={this.state.属性名称} 父组件接受数据函数名称={this.getData}/>
    });
  }
}

//子组件接受
class Son extends React.Component{
  constructor(props){
    super();
    this.state = props;
  }

  handleClick(需要传递给父组件的值){
    this.props.父组件接受数据函数名称(需要传递给父组件的值)
  }

  render(){
    return(
      <子元素标签 onClick={()=>{
        this.handleClick(需要传递给父组件的值);
      }}>{this.state.子组件属性名称}</子元素标签>


    );
  }

}

兄弟组件

通过子传父,然后再父传子 实现兄弟组件之间的通信

原文地址:https://www.cnblogs.com/mxnl/p/13709021.html