【问题标题】:Reactjs, table cell with different background colorReactjs,具有不同背景颜色的表格单元格
【发布时间】:2018-09-04 18:34:36
【问题描述】:

在我的 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 html reactjs semantic-ui


    【解决方案1】:

    使用 style 代替 bgcolor,因为 HTML5 不再支持它。即使你在没有条件逻辑的情况下尝试它,bgcolor 也不会影响&lt;td&gt;,不管 React。每W3Schools

    HTML5 不支持的 bgcolor 属性。使用 CSS 而是。

    render() 函数内有条件地设置style 属性。这个例子使用@OlivierBoissé 方法有条件地设置值,但你真的可以使用任何你喜欢的条件方法,ESLint 不会抱怨。使用 background-color 时,您可以使用 CSS inherit 作为默认值:

    // 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 示例。

    希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      创建一个函数

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

      还有&lt;Cell {...getColor()} /&gt;

      【讨论】:

      • 谢谢,但现在我明白了 [eslint] 不要嵌套三元表达式。 (无嵌套三元)
      【解决方案3】:

      你可以声明一个变量并使用条件来确定它的值

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2013-06-15
        • 1970-01-01
        相关资源
        最近更新 更多