简体   繁体   English

如何在反应中将 class 分配给 map 中的每个第 n 个 div 元素?

[英]How can I assign a class to every nth div element in map, in react?

How can I assign a class to every nth div element in map, in react?如何在反应中将 class 分配给 map 中的每个第 n 个 div 元素? Here is my code:这是我的代码:

const users = [{name: 'Max'}, 
               {name: 'Pete'}, 
               {name: 'Ben'}, 
               {name: 'Bruce'}];

return ({users.map(({name})=>{
  return (
    <div className="users">{name}</div>
);
)})

How can I assign a different class to every 2nd div element?如何为每个第二个 div 元素分配不同的 class ?

You can use index inside map callback function to get current index.您可以使用map回调 function 中的索引来获取当前索引。

return ({users.map(({name},index)=>{
  if(index%2==1){
   return (
    <div className="users">{name}</div>
); 
  }
   return (
    <div>{name}</div>
);
});});

While it is possible to do this via the second parameter in the map callback, as per @TusharShahi's answer, you may not need to do this at all.虽然可以通过map回调中的第二个参数来执行此操作,但根据@TusharShahi 的回答,您可能根本不需要这样做。 Using the :nth-child() CSS selector, you can just apply the same class to all elements and use CSS to mark every n th element:使用:nth-child() CSS 选择器,您可以将相同的 class 应用于所有元素并使用 CSS 标记每个第n个元素:

Make every 5th element red:使每 5 个元素变为红色:

.users:nth-child(5n){
    color:red;
}

Make every even element blue:使每个偶数元素变为蓝色:

.users:nth-child(even){
    color:blue;
}

See runnable code below:请参阅下面的可运行代码:

 .users:nth-child(5n) { color: red; }
 <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div> <div class="users">user</div>

Depending on your needs, you might also achieve this only with CSS, using the:nth-child pseudo-class:根据您的需要,您也可以仅使用 CSS 实现此目的,使用:nth-child 伪类:

 div {color:blue;} div:nth-child(even){color:red;}
 <div>Max</div> <div>Pete</div> <div>Ben</div> <div>Bruce</div>

if your HTML is becoming more complex, and you need to style children nodes under this div, this is probably NOT the best option, and giving a class makes sense, but I thought it was worth mentioning.如果您的 HTML 变得越来越复杂,并且您需要在此 div 下设置子节点的样式,这可能不是最佳选择,并且提供 class 是有道理的,但我认为值得一提。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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