javascript - 当当前迭代在反应中为真时,如何将类添加到先前的迭代?
问题描述
当当前迭代为真时,我在向先前迭代添加类时遇到了一些问题,有人可以帮助我吗?
所以我正在绘制盒子,并为盒子添加类。如果某些条件为真,但现在我想如果当前循环的条件为真,则将类添加到上一个框。这是代码
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 加课等等。有人可以帮我吗?
解决方案
这是解决此问题的一种方法。在渲染之前,找到最后一个为真的框的索引。渲染时检查当前索引是否小于或等于最后一个真实索引,然后添加 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 / > ))
}
推荐阅读
- python - 取一个数据框的多列来创建另一个包含两列的数据框
- angular - 获取在 FormGroup 或 FormArray 中被修改的控件的名称
- sql - 包含整数的 alpha 列上的 WHERE 子句在整数比较中失败
- javascript - 如何将状态添加到动态 UI 控件中?
- c - 总是出现分段错误
- macos - 如何在 Metal 中制作模板化计算内核
- java - 如何从我的 testng 报告中获取控制台输出?
- npm - mapbox-map-image-export 在 Ubuntu 服务器上返回一个未指定的错误“Error {}”
- google-cloud-dataflow - 是什么导致我的 Dataflow 作业被取消?
- python - scipy.optimize.dual_annealing 中允许哪些“访问”参数值?