【问题标题】:How to conditionaly add "class" in Reactjs如何在 React Js 中有条件地添加 \"class\"
【发布时间】:2022-11-17 15:24:10
【问题描述】:

我正在使用 Reactjs 并且正在使用 nextjs,现在我正在尝试集成/获取滑块数据,问题是我只想将类“活动”添加到第一张幻灯片,所以我正在尝试使用 {post.id},但是我如何使用条件(在 id="1" 处添加“活动”类)?那么我如何使用 loop/mapfunction 来做到这一点?这是我当前的代码

   <div className={`carousel-item ${post.id === 1 ? 'active' : ''}`}>
                                  <img src="img/blog-slider.png" className="d-block w-100" alt="..." />
                                  <div className="carousel-caption  d-md-block">
                                    <h5>MBG starts Their Journey</h5>
                                    <p>Along with collecting as much data and information as possible, completing their research, and making their plan, the MBG team has now begun to implement their plan in detail, and they are in the initial steps. With the completion of any step, the MBG team will inform you about the latest news and information</p>
                                  </div>
                                </div>

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    你可以简单地这样做:

    <div className={`carousel-item ${post.id == 1 ? 'active' : ''}`}>
    

    【讨论】:

    • 当它是“1”作为严格相等的字符串时,它可能会失败
    • 是的,你是对的,我更新了我的答案,谢谢@KcH
    【解决方案2】:

    可以参考this的文章或者this的一篇。

    stackoverflow 上也有一个。

    【讨论】:

      【解决方案3】:

      使用 index 我们可以得到如下条件

      <>
        <div className={`carousel-item ${index === 0 ? "active" : ""}`}></div>
      </>;
      

      或 - 根据您提到的条件

      <>
        <div className={`carousel-item ${post.id == 1 ? "active" : ""}`}></div>
      </>;
      

      【讨论】:

        【解决方案4】:
        {this.state.trending.map((post, index) => {
        var dt = post.CreatedAt;
          return (
                   <>
                   <div className={post.id == ‘1’ ? ‘carousel-item’ : ‘’>
                   </>
                  )
                 })}
        

        欲了解更多信息,请结帐

        三元运算符

        【讨论】:

          猜你喜欢
          • 2016-08-01
          • 2017-01-09
          • 2017-03-25
          • 1970-01-01
          • 1970-01-01
          • 2017-08-29
          • 1970-01-01
          • 2017-04-20
          相关资源
          最近更新 更多