在我的 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 :
The bgcolor attribute of is not supported in HTML5. Use CSS instead.
设置style
render()
内有条件的属性(property)功能。此示例使用 @OlivierBoissé 方法有条件地设置值,但您实际上可以使用任何您熟悉的条件方法,ESLint 不会提示。您可以使用 CSS inherit
作为使用 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示例。
希望对您有所帮助!
关于javascript - Reactjs,具有不同背景颜色的表格单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172172/