如何为表格中的特定单元格着色

问题描述:

我的ReactJS应用程序中有一个HTML Table,我想为那里的特定单元格或行设置颜色。我有我的阵列状态,并希望检查相邻行之间的差异,然后通过将它们着色为红色来显示这些差异。如何为表格中的特定单元格着色

class MainTable extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     results: [] 
    }; 
    } 
    render() { 
    const sorted = _.sortBy(this.state.results, ['ORIGIN', 'DATASTAMP']); 
    return (
     <div> 
     <div> 
      <Table hover striped bordered responsive size="sm"> 
      <thead> 
       <tr> 
       <th>VERSION</th> 
       <th>DATE</th> 
       <th>ORIGIN</th> 
       </tr> 
      </thead> 
      <tbody> 
       {sorted.map(result => 
       <tr> 
        <td>{result.VERSION}</td> 
        <td>{result.DATASTAMP}</td> 
        <td>{result.ORIGIN}</td> 
       </tr> 
      )} 
      </tbody> 
      </Table> 
     </div> 
     </div> 
    ); 
    } 
} 

我不知道该怎么做。也许有一些想法?对不起noobie问题,我是ReactJS

+0

css类,元素样式?? – philipp

+0

但我应该如何标记数组中的特定元素? –

您可以使用类似

<tr style={{'background-color': result.color}}>...</tr> 

<tr style={{'background-color': shouldHighlight[key] ? 'red' : 'white'}}>...</tr> 

很明显,在第二种情况下,您需要在函数之前查找,应该突出显示哪些表行,并将其存储在数组中。

此外,您需要编写格式为(result, key) => ...的地图功能,或者您需要知道结果的编号。

为了纪念某些行您可以:

{sorted.map((result, index) => 
    <tr className={`item-${index}`}> 
     <td>{result.VERSION}</td> 
     <td>{result.DATASTAMP}</td> 
     <td>{result.ORIGIN}</td> 
    </tr> 
)} 

基本上你首先需要对其中的一些标准,以纪念你的元素,比你可以申请一个类或样式它。乐于助人是classnames所以你可以做这样的事情:

{sorted.map((result, index) => 
    <tr className={classnames({ 
    even: index % 2 == 0, 
    odd: !(index % 2 == 0) 
    })}> 

这要么evenodd添加到<row>的类别,根据在列表中的索引。

我想有只有两件事情要牢记:

  1. 元素的样式需要的对象,如:{ backgroundColor: #000 }
  2. CSS类需要被添加为»的className«财产

您可以在数组的每个元素中添加一个标志,以指示是否需要设置单元格的背景颜色。

,然后用它像这样在你的渲染方法:

render() { 
const sorted = _.sortBy(this.state.results, ['ORIGIN', 'DATASTAMP']); 
return (
    <div> 
    <div> 
     <Table hover striped bordered responsive size="sm"> 
     <thead> 
      <tr> 
      <th>VERSION</th> 
      <th>DATE</th> 
      <th>ORIGIN</th> 
      </tr> 
     </thead> 
     <tbody> 
      {sorted.map(result => 
      <tr className={(result.colorFlag ? 'colored-background' : '')}> 
       <td>{result.VERSION}</td> 
       <td>{result.DATASTAMP}</td> 
       <td>{result.ORIGIN}</td> 
      </tr> 
     )} 
     </tbody> 
     </Table> 
    </div> 
    </div> 
); 

,当然还有,别忘了创建CSS类

.colored-background { 
    background-color: #BADA55; 
}