【问题标题】:REACT JS - increment component className?REACT JS - 增加组件类名?
【发布时间】:2020-08-06 03:12:23
【问题描述】:

有一个问题,如果可以在 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>

你有答案吗?还是更好的方法?

谢谢。

(我是法国人,如果我在英语中犯了错误,我真的很抱歉)

【问题讨论】:

  • 类名是字符串。两个字符串的连接是你必须做的。一个字符串是名称,另一个是索引。

标签: html css reactjs increment classname


【解决方案1】:

第二个参数是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>
     </>
     );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2020-11-18
    • 2018-08-15
    • 2022-06-26
    • 1970-01-01
    • 2021-03-19
    • 2016-11-24
    相关资源
    最近更新 更多