如果我正确理解您的问题,您正在寻找类似 @987654322@ React 传递给每个组件的特殊道具(来自文档)
这特别适用于您不知道组件的子项将提前做什么的情况。
在你的情况下,这可以大致如下实现 -
class Products extends React.Component {
render() {
/* this.props.children here will be an array of all
* the children which can be custom components
* enclosed within the <Products> component
* when it is rendered
*/
return (
<div className='products'>
{this.props.children}
</div>
)
}
}
在实际场景中,如果您想将 ProductDetail 组件嵌套在 Products 组件内,因为您希望 Products 以某种方式将一些 prop 传递给它包含的每个 ProductDetail,您可以使用React.Children (docs) 提供的各种有据可查的实用程序
所以一个实际的例子如下 -
class Products extends React.Component {
getTransformedChildren() {
return React.Children.map(this.props.children, child => {
// if child is of type ProductsDetail, clone it so you can
// pass your own prop to it else return the child
const newChild = (child.type === ProductsDetail) ?
React.cloneElement(child, { category: this.props.category }) :
child
return newChild
}
render() {
return (
<div className='products'>
{this.getTransformedChildren()}
</div>
)
}
}
所以你的渲染语句如下所示:
<Products category='groceries'>
<ProductDetails id='1' />
<ProductDetails id='2' />
<HelloWorld />
</Products>
在这种情况下,所有内部 ProductDetails 子级将有一个属性 categories 设置为 groceries。但是,内部的HelloWorld 组件不会被传递categories 属性,因为它不是ProductDetails 类型。
使用此范例的另一个实际应用是,如果您希望父自定义组件将内联样式传递给它的全部或部分子组件,并且如果您正在编写自己的库,这将非常有用。