zoukankan      html  css  js  c++  java
  • react 嵌套组件的通信

    在react中经常会用到的组件嵌套,如下:

    图中 parent本身是一个自定义的组件,然后内部又加入了 child的自定义组件,那么这种情况,父子之间如何通信

    react中在父组件里面有一个 this.props.children  当没有子组件时,值为 undefined ,只有一个子组件时,为一个对象,多个子组件时为一个数组

    我们可以使用react提供的方法遍历子组件,并且绑定

    代码如下:

    child.jsx

    import React, { Component } from 'react';
    
    
    
    
    
    class Child extends Component {
    	constructor(props){
    		super(props);
        	this.state = {date: new Date()};
      }
      showValue=()=>{
        this.props.showValue && this.props.showValue()
      }
      render() {
        return (
          <div className="Child">
           	<div className="content">
               Child
               <button onClick={this.showValue}>调用父的方法</button>
           	</div>
          </div>
        );
      }
    }
    
    export default Child;
    

      

    在 parent.jsx中

    import React, { Component } from 'react';
    
    
    class Parent extends Component {
    	constructor(props){
    		super(props);
        	this.state = {date: new Date()};
      }
      showValue=()=>{
        console.log("showValue....")
      }
      renderChildren(props) {
        //遍历所有子组件
        return React.Children.map(this.props.children, child => {
            var childProps = {
              //把父组件的props.name赋值给每个子组件(父组件传值给子组件)
              name: props.name,
              //父组件的方法挂载到props.showValue上,以便子组件内部通过props调用
              showValue:this.showValue
            };
            return React.cloneElement(child,childProps );
        });
      }
      render() {
        return (
          <div className="Parent">
           	<div className="content">
               Parent
               {this.renderChildren(this.props)}
           	</div>
          </div>
        );
      }
    }
    
    export default Parent;
    

      

    关键在于:遍历内部的子组件,然后动态的给子组件绑定props

  • 相关阅读:
    HTTPHelper
    C# 捕获全局亲测可用
    C# Excel的读写
    C# combox 绑定数据
    MySQL在CenterOS和Ubuntu的安装
    VMware虚拟机里的Centos7的IP
    Docker安装和部署
    linux安装git方法(转)
    mysql安装最后一步 Apply Security Settings 出错
    Linux下安装MySQL
  • 原文地址:https://www.cnblogs.com/muamaker/p/9640442.html
Copyright © 2011-2022 走看看