假设您有一个呈现文本的子组件,如下所示:
export const RatingsGoneBetter = () => (
<TestContainer>
<section>
<h1>What could’ve gone better with {this.props.getName()}?</h1>
</section>
</TestContainer>
)
父母......
class TestContainer extends React.Component {
constructor (props) {
super(props)
}
getName () {
const { userId, chef, john } = this.props
if (userId === 50) {
return john.name
} else if (userId === 1) {
return chef.name
}
}
render () {
return (
<div>{this.props.children}</div>
)
}
}
如何调用子节点中的getName方法来呈现正确的名称?
答案 0 :(得分:1)
要将props
添加到children
元素,您可以使用React.cloneElement
。您还需要将子项分成单独的组件,以便您可以使用cloneElement
相关代码段:
const RatingsGoneBetter = props => (
<TestContainer userId={1} chef={{ name: "codesandbox" }}>
<Sample />
</TestContainer>
);
const Sample = props => {
return (
<section>
<h1>What could’ve gone better with {props.getName()}?</h1>
</section>
);
};
和TestContainer
render () {
return (
<div>{React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {getName: this.getName()}, null);
})}
</div>
)
}
<强> Working CodeSandbox 强>