[英]i am create an array in react to print images select only images i want based on to numbers
i am running into a tricky problem, i am creating an array of 100 elements, and mapping through it an generating an image for each:我遇到了一个棘手的问题,我正在创建一个包含 100 个元素的数组,并通过它映射为每个元素生成一个图像:
{Array.from({ length: 100 }).map((_, i) => ( <> <img key={i} className={`h-12 object-contain cursor-pointer `} src="/images/panneau.png" alt="" /> </> ))}
The problem you are tying to solve is converting a flat array index to a 2 dimentional array indexes, then you can use those to apply conditional code.您要解决的问题是将平面数组索引转换为二维数组索引,然后您可以使用它们来应用条件代码。
Let's say you want to have 10 images for each row, I am calling this WIDTH.假设您希望每行有 10 张图像,我称之为 WIDTH。
you can get the current row index with the formula: y = Math.floor(i / WIDTH);您可以使用以下公式获取当前行索引: y = Math.floor(i / WIDTH); and you can get the current index in each row with: x = i % WIDTH;
您可以使用以下命令获取每行中的当前索引: x = i % WIDTH;
now that you have those you can do something like:现在你有了那些你可以做的事情:
function MyComponent() { const WIDTH = 10; //number of images in one row return <> {Array.from({ length: 100 }).map((_, i) => { x = Math.floor(i / WIDTH); y = i % WIDTH; opacity = (x <= 5) && (y <= 4)? ' opacity-50': ''; return ( <img key={i} className={`h-12 object-contain cursor-pointer` + opacity} src="/images/panneau.png" alt="" /> ); })} </> }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.