• 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.子组件属性名称}</子元素标签>
    
    
        );
      }
    
    }
    

    兄弟组件

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

  • 相关阅读:
    常见存储过程分页PK赛——简单测试分析常见存储过程分页速度
    简单的ASP.NET无刷新分页
    程序员45个好习惯
    手机应用兼职开发平台,欢迎有识之士参加...
    DotNetRemoting分布式安全部署(整理+原创)
    刚刚整理的截获SQL错误代码弹出提示信息类.
    485modbus通讯协议
    485通信
    ucoss在stm32上的移植
    使用OFFICE组件出问题环境配置
  • 原文地址:https://www.cnblogs.com/mxnl/p/13709021.html
Copyright © 2020-2023  润新知