在我的React应用程序中,我有一个表(使用语义ui)。我想通过条件改变bgcolor
。在大多数示例中,我看到像bgcolor={(condition)?'red':'blue'}
但我需要检查数组中是否存在值。所以,如果值在arrayOne
应用bgcolor
,如果值在arrayTwo
应用另一种颜色否则没有bgcolor
我试过这个是错的
<Table.Cell
key={value}
selectable
{...arrayOne.includes(value)?{bgcolor="red"}:{}}
{...arrayTwo.includes(value)?{bgcolor="blue"}:{}}
>
{value}
</Table.Cell>
使用style
而不是bgcolor
,因为它不再受HTML5支持。即使您在没有条件逻辑的情况下尝试它,bgcolor
也不会影响<td>
,无论React如何。每W3Schools:
HTML5中不支持bgcolor属性。请改用CSS。
在style
函数内有条件地设置render()
属性。此示例使用@OlivierBoissé方法有条件地设置值,但您可以使用任何您熟悉的条件方法,并且ESLint不会抱怨。使用inherit
时,可以使用CSS background-color
作为默认值:
// default
let backgroundColor = 'inherit';
if (arrayOne.includes(value)) {
backgroundColor = 'red';
} else if (arrayTwo.includes(value)) {
backgroundColor = 'blue';
}
{/* or if you need one color to take precedence when value is in both arrays
if (arrayOne.includes(value)) {
backgroundColor = 'red';
}
if (arrayTwo.includes(value)) {
backgroundColor = 'blue';
}
*/}
<Table.Cell
key={value}
selectable
style={{backgroundColor}}
>
{value}
</Table.Cell>
或者你也可以使用className
而不是style
:
.foo { background-color: red; }
.bar { background-color: blue; }
let backgroundColor = '';
if (arrayOne.includes(value)) {
backgroundColor = 'foo';
} else if (arrayTwo.includes(value)) {
backgroundColor = 'bar';
}
<Table.Cell className={backgroundColor} ...>
这是一个有效的StackBlitz例子。
希望这有帮助!
创建一个功能
getColor = (value) => array2.includes(value) ? {bgcolor:'red'} : array1.includes(value) ? {bgcolor:'blue'} : {}
和<Cell {...getColor()} />
您可以声明变量并使用条件来确定其值
let bgcolor;
if(arrayOne.includes(value)) {
bgcolor = 'red';
} else if( arrayTwo.includes(value)) {
bgcolor = 'blue';
}
然后
<Table.Cell
key={value}
selectable
bgcolor={bgcolor}
>
{value}
</Table.Cell>