在react组件中,经常需要基于传入的props数据创建多个小方格。比如:
<div id="container"> { itemdata.map((item, index) => ( <div key={index} style={{ ... }} > </div> )) } </div>
效果如下:
在此基础上,我们想要给container div添加行号,就像编辑器编辑代码一样,前面显示行号。要实现这一需求,可以采用以下方法:
将左侧的索引设置为absolute,右侧的方块设置为relative,两者的父元素设置为position: relative 且 overflow: hidden;
.app { overflow: hidden; position: relative; } .left-box { position: absolute; left: 0; top: 0; width: 19px; overflow: hidden; } .right-box { margin-left: 19px; }
<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>