3 回答

TA贡献1795条经验 获得超7个赞
制作另一个var“串行组”。在循环之外创建另一个计数器 j=1 。在循环中将序列添加到序列组,然后如果 j 为 3,则将序列的 div 推入序列并将 j 重置为 1。所有这一切都说,你最好使用 CSS 来完成这种格式化......这是一个 CSS 示例:循环外:
const serialdivstyle = {
display:'inline-block',
width: '28%',
margin: '2%',
border-left: '1px solid black',
text-align: 'center'
};
循环内部(注意删除条形字符):
var serial = (
<div style={serialdivstyle}>
{scannedItems[i]}
</div>
)

TA贡献1757条经验 获得超8个赞
我的想法是将元素数组分块,然后生成模板。
const chunk = (elements, groupSize) =>
elements.reduce((acc, nextElement, index) => {
const row = Math.floor(index / groupSize);
if (acc[row] === undefined) {
acc.push([nextElement]);
} else {
acc[row].push(nextElement);
}
return acc;
}, []);
const buildLayout = elements => (
<div className="table">
{elements.map((row, rowIndex) => {
return (
<div className="row" key={rowIndex}>
{row.map(column => (
<div className="column" key={column}>
{column}
</div>
))}
</div>
);
})}
</div>
);
const elements = [1, 2, 3, 4, 5, 6, 7];
const chunks = chunk(elements, 3);
const layout = buildLayout(chunks);

TA贡献2051条经验 获得超10个赞
这可能有点矫枉过正,但我会采用批处理方法。使其可重复使用且更清洁。
像这样的东西。
interface Array<T> {
chunk(size: number): Array<T>;
}
Array.prototype.chunk = function<T>(this: T[],size: number) {
var temporal = [];
for (var i = 0; i < this.length; i+= size){
temporal.push(this.slice(i,i+size));
}
return temporal;
}
然后只使用简单的数组。
const listOfItems= ["aaaaaa", "aaaaaa", "aaaaaa", "aaaaaa"].chunk(3);
抱歉刚刚注意到它是 Javascript 而不是打字稿,代码将是:
Array.prototype.chunk = function (size) {
var temporal = [];
for (var i = 0; i < this.length; i += size) {
temporal.push(this.slice(i, i + size));
}
return temporal;
};
添加回答
举报