react 嵌套组件的通信

本文介绍React中父组件与子组件间通信的实现方法,通过遍历子组件并动态绑定props,展示如何在子组件中调用父组件的方法。

在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

 

转载于:https://www.cnblogs.com/muamaker/p/9640442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值