如何在单个id中呈现多于组件,我知道单个id不能呈现多个组件,我也尝试getElementByClass
但结果是相同的
function Ads(product) {
return(
<div className={product.className} id="user-ads">
<div className = "col-sm-6 col-md-5">
<div className = "thumbnail">
<img src={product.image} alt="product-image"/>
</div>
<div className = "caption">
<div className="border">
<h3>{product.title}</h3>
<p>{product.desc}</p>
<button className = "btn btn-primary" role = "button" data-toggle="modal" data-target="#view-detail">View Details
</button>
</div>
</div>
</div>
</div>
);
}
function Newad(product) {
return (
<Ads title="Forza" desc="rndom text rndom text rndom text rndom text" image="img/img2.jpg" />
);
}
ReactDOM.render(<Ads title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum" image="img/img1.jpg" className="row" />, document.getElementById('all_ads'));
ReactDOM.render(<Newad />, document.getElementById('all_ads'));
答案 0 :(得分:0)
你为什么要那样做?这不是反应如何运作。应该有一个安装点,所有其他组件应该在该安装点
之下因此,在您渲染Newad
的情况下,它会自动调用在Newad中声明的Ads
。
如果您要将多个广告传递参数列入NewAd
添加组件,而不是通过不同的ID再次呈现它。
答案 1 :(得分:0)
以下两种解决方案中的任何一种都可以用于您的预期用途吗?
此外,您可能会发现此问题很有用:Return multiple elements inside React.render()
解决方案1: http://codepen.io/PiotrBerebecki/pen/RGoJvB
function Newad(product) {
return (
<div className={product.className} id="user-ads">
<div className="col-sm-6 col-md-5">
<div className="thumbnail">
<img src={product.image} alt="product-image"/>
</div>
<div className="caption">
<div className="border">
<h3>{product.title}</h3>
<p>{product.desc}</p>
<button className="btn btn-primary" role="button" data-toggle="modal" data-target="#view-detail">
View Details
</button>
</div>
</div>
</div>
</div>
);
}
function Ads() {
return (
<div>
<Newad title="Forza" desc="rndom text rndom text rndom text rndom text" image="https://placeimg.com/200/200/nature" className="row" />
<Newad title="PlayStation 4" desc="Lorem ipsum jipsum Lorem ipsum jipsum" image="https://placeimg.com/200/200/tech" className="row" />
</div>
);
}
ReactDOM.render(<Ads />, document.getElementById('all_ads'));
解决方案2: http://codepen.io/PiotrBerebecki/pen/NRbBrA
或者,您可以将广告存储在一个对象数组中,然后使用map()
方法迭代它们。
以下是代码:
const ADS = [
{
title: "Forza",
desc: "rndom text rndom text rndom text rndom text",
image: "https://placeimg.com/200/200/nature",
className: "row"
},
{
title: "PlayStation 4",
desc: "Lorem ipsum jipsum Lorem ipsum jipsum",
image: "https://placeimg.com/200/200/tech",
className: "row"
},
];
function Ads() {
return (
<div>
{ADS.map((product, index) => {
return (
<div key={index} className={product.className} id="user-ads" >
<div className="col-sm-6 col-md-5">
<div className="thumbnail">
<img src={product.image} alt="product-image"/>
</div>
<div className="caption">
<div className="border">
<h3>{product.title}</h3>
<p>{product.desc}</p>
<button className="btn btn-primary" role="button" data-toggle="modal" data-target="#view-detail">
View Details
</button>
</div>
</div>
</div>
</div>
);
})}
</div>
);
}
ReactDOM.render(<Ads />, document.getElementById('all_ads'));