REACT JS - 增加组件类名?
REACT JS - increment component className?
有一个问题,是否可以在 React JS 中增加类名???
做这样的事情:
/* 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>
你有答案吗?或者更好的方法?
谢谢。
(我是法国人所以如果英文写错了真的很抱歉)
第二个参数是map函数的数组索引。因此,您可以将 renderRow 函数更改为此并将索引作为道具传递。
renderRow(item, index) {
return (
<article class="photo__item">
<PhotosFigure index={index+1} />
</article>
);
}
然后在您的 PhotosFigure
组件中,您可以接收索引作为道具并将样式应用于您的 class,如下所示:
class PhotosFigure extends React.Component{
render (){
return (
<>
<div className={`figure photo_${this.props.index}`}></div>
</>
);
}
}
有一个问题,是否可以在 React JS 中增加类名???
做这样的事情:
/* 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>
你有答案吗?或者更好的方法?
谢谢。
(我是法国人所以如果英文写错了真的很抱歉)
第二个参数是map函数的数组索引。因此,您可以将 renderRow 函数更改为此并将索引作为道具传递。
renderRow(item, index) {
return (
<article class="photo__item">
<PhotosFigure index={index+1} />
</article>
);
}
然后在您的 PhotosFigure
组件中,您可以接收索引作为道具并将样式应用于您的 class,如下所示:
class PhotosFigure extends React.Component{
render (){
return (
<>
<div className={`figure photo_${this.props.index}`}></div>
</>
);
}
}