我有react组件,它从map函数获取索引,我试图在索引为偶数时打开行标记的div,并在索引为奇数时关闭它
render() {
return (
{this.props.index%2===0 && (<div className="row mt-1">)} //new row
<div className="col-1">{this.props.title}</div>
<div className="col-5">
<ProgressBar
variant={this.props.color}
now={this.props.now}
max={this.props.max}
label={this.props.label}
/>
</div>
{this.props.index%2===1 && (</div>)} //end of the row
);
}
此代码无法编译: enter image description here
关键是每一行都包含两个 ProgressBar 。正确的方法是什么?
答案 0 :(得分:1)
您需要处理整个元素一次,而不是标签。
如果将其分解为功能,则更容易。
您可以在数组上使用splice
一次抓取两个项目。
例如
function createRow(elements) {
return (
<div>
{elements.map(createProgressBar)}
</div>
);
}
function createProgressBar(element) {
return (
<div>{element.index}</div>
);
}
function render() {
// ...
const rows = [];
while (myArray.length) {
const thisRow = myArray.splice(0,2);
rows.push(createRow(thisRow));
}
return rows;
}
答案 1 :(得分:1)
在尝试渲染数组之前,应将其形状修改为类似的形状。
[1,2,3,4] => [[1,2],[3,4]]
那样,您可以更轻松地将其包装在div
中。
请参见live demo
将平面数组转换为嵌套数组的代码:
const list = [1, 2, 3, 4];
const [state, setState] = React.useState([]);
React.useEffect(() => {
let res = [];
for (let i = 0; i < list.length; i += 2) {
res.push([list[i], list[i + 1]]);
}
setState(res);
}, []);
渲染逻辑:
{state.map(item => {
return (
<div style={{ border: "1px solid black", padding: "1em" }}>
{item.map(i => i)}
</div>
);
})}