Reactjs,具有不同背景颜色的表格单元格

问题描述 投票:1回答:3

在我的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>
javascript html5 reactjs semantic-ui
3个回答
4
投票

使用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例子。

希望这有帮助!


1
投票

创建一个功能

getColor = (value) => array2.includes(value) ? {bgcolor:'red'} : array1.includes(value) ? {bgcolor:'blue'} : {}

<Cell {...getColor()} />


0
投票

您可以声明变量并使用条件来确定其值

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>
© www.soinside.com 2019 - 2024. All rights reserved.