2017-07-26 110 views
0

我的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

但我應該如何標記數組中的特定元素? –

回答

0

您可以使用類似

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

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

很明顯,在第二種情況下,您需要在函數之前查找,應該突出顯示哪些錶行,並將其存儲在數組中。

此外,您需要編寫格式爲(result, key) => ...的地圖功能,或者您需要知道結果的編號。

1

爲了紀念某些行您可以:

{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«財產
0

您可以在數組的每個元素中添加一個標誌,以指示是否需要設置單元格的背景顏色。

,然後用它像這樣在你的渲染方法:

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; 
} 
相關問題