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

  • 相关阅读:
    多线程GCD(二)
    多线程
    Runtime & Runloop
    MTK android 重启测试脚本
    ubuntu samba 配置简介
    Gerrit使用简介
    MTK andorid从底层到上层添加驱动
    MTK GPIO 新增变量配置
    MT6755 使用R63350 IC 出现唤醒概率性闪白,并导致ESD FAIL
    android L版本AAL新架构
  • 原文地址:https://www.cnblogs.com/muamaker/p/9640442.html
Copyright © 2011-2022 走看看