当当前迭代为真时,如何将类添加到前一次迭代中? [英] How to add class to previous iteration when current Iteration is true in react?

查看:52
本文介绍了当当前迭代为真时,如何将类添加到前一次迭代中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当当前迭代为 true 时,我在将类添加到前一个迭代时遇到了一些问题,有人可以帮助我吗?

I'm facing some issue in adding class to previous iteration when current iteration is true can someone help me in this?

所以我正在绘制 Box,并向 Box 添加类.如果某些条件为真,但现在我想要当前循环的条件是否为真,将类添加到前一个框.这是代码

So I'm drawing the Box, and adding class to Box. If some condition is true, But Now I want if condition is true for current loop, add class to previous box. Here is the code

 const addClass=(isTrue)=>{debugger
    let name=""
    if(isTrue){
       name="setLine"
    }
    return name
  }

const getValue = (item, depotName) => {
    let count = "";
    for(let i=0;i<item?.length;i++){
       if(item[i].from===depotName&&item[i-1].to===depotName){
        count=item[i].qty+item[i-1].qty;
      
       }
    }
    return count;
  };


 {item?.depots?.distribution?.map((depot, index) => (
                   
                      <div className={`multi-spply-container ${addClass( getValue(item, depot.depotName)}`} key={index}>
                      <Box/>))}

所以现在发生的事情是假设有 3 个框,并且第 2 个框和第 3 个框为真(这是条件),仅对于正在添加的框类(setLine").但是我想要的是第二个框是真的我也想将类添加到第一个框.假设第三个框是真的,我想将课程添加到第一个和第二个等等.有人可以帮我吗?

So now what happening is suppose there is 3 box, and 2nd box and 3rd box is true(this is the condition) only for that box class is adding("setLine"). But what I want is as 2nd box is true I want to add class to 1st Box also . Suppose 3rd box is true I want to add class to 1st and 2nd So on.Can Someone help me on this please?

推荐答案

这是解决此问题的一种方法.在渲染之前,找到最后一个框的索引为真.渲染时检查当前索引是否小于或等于最后一个真实索引,然后添加类 setLine.

Here is one way to solve this. Before rendering, find the index of the last box that is true. While rendering check if the current index is less than or equal to the last true index then add class setLine.

const addClass = (isTrue) => {
  debugger
  let name = ""
  if (isTrue) {
    name = "setLine"
  }
  return name
}

const getValue = (item, depotName) => {
  let count = "";
  for (let i = 0; i < item ? .length; i++) {
    if (item[i].from === depotName && item[i - 1].to === depotName) {
      count = item[i].qty + item[i - 1].qty;
    }
  }
  return count;
};

// Find last index which is true
let lastTrueIndex = -1;
item?.depots?.distribution?.forEach((depot, index) => {
  if (getValue(item, depot.depotName)) {
    lastTrueIndex = index;
  }
});


// If the index of the box in the iteration is less than or equal to
// last true index then add class setLine.
{
  item?.depots?.distribution?.map((depot, index) => (
  <div className = {
    `multi-spply-container ${index <= lastTrueIndex ? "setLine" : ""}`
  }
  key = {index} />
  <Box / > ))
}

这篇关于当当前迭代为真时,如何将类添加到前一次迭代中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆