如下可以将 id = 1 作为 props 传入每个子组件中,注意要使用返回值作为新的 children,原来的 children 并没有发生改变
React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
id: 1,
});
})
详细示例如下
import React, { PureComponent } from 'react';
export default class DecorateChildren extends PureComponent {
render() {
return (
<Parent>
<Child />
</Parent>
)
}
}
class Parent extends PureComponent {
getDecoratedChildren = () => {
return React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
id: 1,
});
})
}
render() {
return (
<div>{this.getDecoratedChildren()}</div>
)
}
}
class Child extends PureComponent {
render() {
const { id } = this.props;
return (
<div>{id}</div>
)
}
}