简体   繁体   中英

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:

 {Array.from({ length: 100 }).map((_, i) => ( <> <img key={i} className={`h-12 object-contain cursor-pointer `} src="/images/panneau.png" alt="" /> </> ))}

here is what i get: 在此处输入图像描述 what i want:

  • for example i have tow numbers 5 and 6 i want to add opacity-50 to this images in the range of 6 * 5: 在此处输入图像描述

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.

you can get the current row index with the formula: y = Math.floor(i / WIDTH); and you can get the current index in each row with: 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="" /> ); })} </> }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM