首页 > 解决方案 > 当当前迭代在反应中为真时,如何将类添加到先前的迭代?

问题描述

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

所以我正在绘制盒子,并为盒子添加类。如果某些条件为真,但现在我想如果当前循环的条件为真,则将类添加到上一个框。这是代码

 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”)。但我想要的是第二个盒子是真的,我也想给第一个盒子添加类。假设第 3 个框是真的我想给第 1 和第 2 加课等等。有人可以帮我吗?

标签: javascriptreactjsloopsfor-loop

解决方案


这是解决此问题的一种方法。在渲染之前,找到最后一个为真的框的索引。渲染时检查当前索引是否小于或等于最后一个真实索引,然后添加 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 / > ))
}

推荐阅读