react 嵌套组件的通信

时间:2023-03-10 01:43:03
react 嵌套组件的通信

在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