
如何在 react 组件的 map 循环中为创建的 div 添加行号
当在 react 组件中使用 map 循环创建多个元素时,经常需要给这些元素添加行号。下面是如何实现这一需求:
将行号和方格放置在各自的容器中,并将它们定位为相对容器。为了隐藏超出容器的部分,可以设置容器为相对,并设置溢出设置为隐藏。
css 代码如下:
.container {
overflow: hidden;
position: relative;
}
.left-box {
position: absolute;
left: 0;
top: 0;
width: 19px;
overflow: hidden;
}
.right-box {
margin-left: 19px;
}jsx 代码如下:
import React from "react";
const App = () => {
const itemData = new Array(50).fill(0);
const indexData = new Array(20).fill(0);
return (
{/* 左侧的行号容器 */}
{indexData.map((item, index) => (
{index}
))}
{/* 右侧的方格容器 */}
{itemData.map((item, index) => (
))}
);
};
export default App;通过上述设置,左侧容器将包含行号,右侧容器将包含方格,并且每个方格上方都显示一个相应行号。










