我仍然是 React 的菜鸟,在互联网上的许多示例中,我看到了渲染子元素的这种变化,这让我感到困惑。通常我会看到这样的:
class Users extends React.Component {
render() {
return (
<div>
<h2>Users</h2>
{this.props.children}
</div>
)
}
}
但后来我看到了这样的例子:
<ReactCSSTransitionGroup
component="div"
transitionName="example"
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
>
{React.cloneElement(this.props.children, {
key: this.props.location.pathname
})}
</ReactCSSTransitionGroup>
现在我理解了 api,但是 docs不太清楚我什么时候应该使用它。
那么,有什么事情是一个人能做而另一个人却不能做的呢?有人可以用更好的例子向我解释这一点吗?
请您参考如下方法:
props.children
不是真正的 child ;它是 children 的描述符。所以你实际上没有什么需要改变的;您无法更改任何 Prop 或编辑任何功能;您只能从中读取。如果您需要进行任何修改,则必须使用 React.CloneElement
创建新元素 .
一个例子:
组件的主要渲染函数,如App.js
:
render() {
return(
<Paragraph>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}
现在假设您需要添加 onClick
给 Paragraph
的每个 child ;所以在你的 Paragraph.js
你可以这样做:
render() {
return (
<div>
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onClick: this.props.onClick })
})}
</div>
)
}
那么你就可以这样做:
render() {
return(
<Paragraph onClick={this.onClick}>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}
注意:React.Children.map
函数只会看到顶级元素,它看不到这些元素渲染的任何内容;这意味着您正在向子级提供直接 Prop (此处为 <Sentence />
元素)。如果您需要进一步传递 props,假设您将有一个 <div></div>
<Sentence />
之一内想要使用 onClick
的元素prop 那么在这种情况下你可以使用 Context API 来做到这一点。使 Paragraph
提供商和 Sentence
元素作为消费者。