React中如何实现循环创建div并添加行号?
在react中循环创建div时,想要添加行号,可以考虑以下设计:
左侧的索引可以设置为绝对定位(absolute),右侧的方块可以设置为相对定位(relative),两者的父元素设置为相对定位且overflow隐藏:
对应的代码如下:
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 ( <div classname="app"> <div classname="left-box"> {indexdata.map((item, index) => ( <div key={index} style={{ fontsize: "9px", width: "19px", height: "20px", margin: "2px", }} > {index} </div> ))} </div> <div classname="right-box"> {itemdata.map((item, index) => ( <div key={index} style={{ display: "inline-block", width: "9px", height: "9px", margin: "2px", backgroundcolor: item.selected ? "green" : "lightgreen", }} ></div> ))} </div> </div> ); } const rootelement = document.getelementbyid("root"); reactdom.render(<app />, rootelement);
.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; }
以上就是React中如何实现循环创建div并添加行号?的详细内容,更多请关注硕下网其它相关文章!