
给 react 组件创建的 div 行号
要给使用 map 循环创建的 div 添加行号,可以采用以下设计方案:
左侧的索引元素设置绝对定位(absolute),右侧的方块设置相对定位(relative),两者的父元素设置相对定位和溢出隐藏(overflow: hidden)。
代码示例:
index.js
import react from "react";
import reactdom from "react-dom";
import "./styles.css";
function app() {
const itemdata = new array(500).fill(0);
const indexdata = new array(20).fill(0);
return (
{indexdata.map((item, index) => (
{index + 1}
))}
{itemdata.map((item, index) => (
))}
);
}
const rootelement = document.getelementbyid("root");
reactdom.render( , rootelement);styles.css
.App {
font-family: sans-serif;
text-align: center;
overflow: hidden;
position: relative;
}
.left-box {
position: absolute;
left: 0;
top: 0;
width: 19px;
overflow: hidden;
}
.right-box {
margin-left: 19px;
}通过这种设计,可以实现使用 map 循环创建的 div 行号效果。










