有一个问题,如果它可以在React JS中递增className吗?
做这样的事情。
/* in first file */
const rowCount = 68;
class PhotosItem extends Component {
constructor() {
super();
this.list = Array(rowCount).fill().map((val, idx) => {
return {
value : 0
}
});
}
render() {
return (
<>
{this.list.map(this.renderRow)}
</>
);
}
renderRow(item) {
return (
<article class="photo__item">
<PhotosFigure />
</article>
);
}
}
export default PhotosItem;
/* in other file */
class PhotosFigure extends React.Component{
render (){
return (
<>
<div className={`figure photo_{* HERE AN INCREMENT *}`}></div>
</>
);
}
}
export default PhotosFigure;
我想要一个这样的渲染。
<article class="photo__item">
<div class="figure photo_1"></div>
</article>
<article class="photo__item">
<div class="figure photo_2"></div>
</article>
[...]
<article class="photo__item">
<div class="figure photo_68"></div>
</article>
Have you an answer for me ? or better way to do that?
thks.
(我是法国人,所以我真的很抱歉,如果我在英语中犯了一个错误)
第二个参数是map函数的数组索引。因此,你可以把renderRow函数改成这个,并把索引作为一个道具传给它。
renderRow(item, index) {
return (
<article class="photo__item">
<PhotosFigure index={index+1} />
</article>
);
}
然后在你的 PhotosFigure
组件,你可以接收索引作为一个道具,并像这样应用样式到你的类中。
class PhotosFigure extends React.Component{
render (){
return (
<>
<div className={`figure photo_${this.props.index}`}></div>
</>
);
}
}