简体   繁体   English

在 React.js 中为数组的不同值设置样式

[英]Styling different values of an array in React.js

I have an array that is getting data from an API, but I want to style each button differently so that the background colours differ.我有一个从 API 获取数据的数组,但我想为每个按钮设置不同的样式,以便背景颜色不同。 I am also using Material UI... Here is my code -我也在使用 Material UI ......这是我的代码 -

{options.map((data, id) => (
 <Button className='p-3 md:w-[25wh] md:h-[25vh]' onClick={handleClickAnswer} fullWidth variant="contained">{decode(data)}</Button>
))}

Please tell me how to style them请告诉我如何设计它们

There are several ways in which you can assign different styles to different buttons.您可以通过多种方式将不同的 styles 分配给不同的按钮。 It can be done majorly using string literals.它可以主要使用字符串文字来完成。

Few examples,几个例子,

  1. If you are using bootstrap/tailwind and your styling will majorly consist of that, then you can something like如果您使用的是 bootstrap/tailwind 并且您的样式主要由它组成,那么您可以使用类似

 {options.map((data, id) => ( <Button className=`p-${id} md:w-[25wh] md:h-[25vh]` onClick={handleClickAnswer} fullWidth variant="contained"> {decode(data)} </Button> ))}

Notice p-${id} would get modified for each particular element in the array注意 p-${id} 将针对数组中的每个特定元素进行修改

  1. Even if bootstrap isn't being used, you can use the above method, create custom classNames to assign styles to each button separately.即使不使用引导程序,您也可以使用上述方法,创建自定义类名,将 styles 分别分配给每个按钮。
  2. If you need to specifically assign a style to the first/last element, you can use first child selector (or) last child selector .如果您需要专门为第一个/最后一个元素分配样式,可以使用第一个子选择器(或)最后一个子选择器

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

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