[英]Passing props.children to a conditionally rendered component
I have Product
component that renders a modal component based on a showModal
boolean value in the Product
component state. 我有
Product
组件,该组件基于Product
组件状态中的showModal
布尔值呈现模态组件。 This is the render method in Product
这是
Product
的渲染方法
render() {
const { .... } = this.props.data;
return (
<>
{this.state.showModal && (
<Modal
product={this.props.data}
toggleModal={this.onToggleModal}
addToCart={this.props.onAddToCart}
/>
)}
<li className="product-body">
<img
src=".."
onClick={this.onToggleModal}
/>
<h2>{...}</h2>
<h3>{..}</h3>
<h3>{..}</h3>
<h2 className="product-price">{...}</h2>
<button type="button" onClick={this.props.onAddToCart}>
Buy now
</button>
</li>
</>
);
}
I want to pass down the content inside li
to the Modal
.How can I make use of props.children
in this case for the Modal
component, so I dont have to pass down the data to be displayed as props ? 我想将
li
内部的内容传递给Modal
。在这种情况下,如何使用props.children
作为Modal
组件,所以我不必传递要显示为props的数据?
If Modal
is another component then you can pass the list as 如果
Modal
是另一个组件,则可以将列表传递为
render() {
const { .... } = this.props.data;
return (
<>
{this.state.showModal && (
<Modal
product={this.props.data}
toggleModal={this.onToggleModal}
addToCart={this.props.onAddToCart}
>
<ListItems {...this.props}/>
</Modal>
)}
<ListItems {...this.props}/>
</>
);
}
Let the ListItems be a separate component as 让ListItems作为一个单独的组件
class ListItems extends React.Component {
render() {
return(
<li className="product-body">
<img
src=".."
onClick={this.onToggleModal}
/>
<h2>{...}</h2>
<h3>{..}</h3>
<h3>{..}</h3>
<h2 className="product-price">{...}</h2>
<button type="button" onClick={this.props.onAddToCart}>
Buy now
</button>
</li>
)}
}
class ListItems extends React.Component {
render(){
return(
<li className="product-body">
<img
src=".."
onClick={this.onToggleModal}
/>
<h2>{...}</h2>
<h3>{..}</h3>
<h3>{..}</h3>
<h2 className="product-price">{...}</h2>
<button type="button" onClick={this.props.onAddToCart}>
Buy now
</button>
</li>
)
}
}
class Wrapper extends React.Component {
render(){
return (
<Modal
product={this.props.data}
toggleModal={this.onToggleModal}
addToCart={this.props.onAddToCart}
>
<ListItems />
</Modal>
)
}
}
class Modal extends React.Component {
render(){
return (
<div>
<h1>Modal Title</h1>
<div>{this.props.children}</div>
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.