【问题标题】:How to add class to previous iteration when current Iteration is true in react?当当前迭代在反应中为真时,如何将类添加到先前的迭代?
【发布时间】:2021-06-26 03:14:47
【问题描述】:

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

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

 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 类添加类等等。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 什么是isTransfer
  • isTransfer 是变量,它为 Box 提供真或假,并且 isTransfer 是根据另一个函数中的某个值进行处理的。
  • 创建一个 sn-p 或代码沙盒来演示这个。
  • 从哪里获得isTransfer 变量?是在分布数组里面吗?
  • 不,它不在数组中,它在另一个函数中处理,在那个函数中它返回真或假。这里我刚才提到了isTransfer

标签: javascript reactjs loops for-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2011-06-28
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多