2016-07-15 46 views
1

我正在嘗試創建一個React表,其中每行都是灰色或白色。我通過在創建時傳遞道具的'灰色'或'白色'來實現這一點,但在我的MyRow類中,我不確定如何採用此道具並將其轉換爲風格。如何用不同顏色的行生成React表?

在MyTable.js相關代碼:

this.props.items.forEach(function(item) { 
     if (i % 2 === 0) { 
      rows.push(<MyRow item={item} key={item.name} color={'gray'} />); 
     } else { 
      rows.push(<MyRow item={item} key={item.name} color={'white'} />); 
     } 
     i++; 
    }.bind(this)); 

MyRow.js渲染功能:

render() { 
    const color = this.props.color; 

    const rowColor = {styles.color}; //?? I’m not sure how to do this—how to get color to take on either gray or white? 

    return (
     <tr className={styles.rowColor}> 
      <td className={styles.td}>{this.props.item.name}</td> 
      <td className={styles.editButton}> <Button 
        onClick={this.handleEditButtonClicked} 
       /> 
      </td> 
     </tr> 
    ); 
} 

MyRow.css:

.td { 
    font-weight: 500; 
    padding: 0 20px; 
} 

.gray { 
    background-color: #d3d3d3; 
} 

.white { 
    background-color: #fff; 
} 
+0

如果您已經定義的CSS類,而你傳遞'className'爲道具,然後就去做''。你爲什麼通過另一個名爲'styles'的對象將'rowColor'傳遞給管道。 'styles'在哪裏定義?它不包含在你的代碼中。 – lux

回答

1

我相信你應該能夠通過直接對該行的prop如下,因爲它已經被定義爲MyTable.js文件中的一個字符串:

render() { 
    return (
     <tr className={this.props.color}> 
      <td className={styles.td}>{this.props.item.name}</td> 
      <td className={styles.editButton}> <Button 
        onClick={this.handleEditButtonClicked} 
       /> 
      </td> 
     </tr> 
    ); 
} 

此外,從已發佈的代碼,其中styles對象位於您正在試圖訪問這些屬性,目前尚不清楚。如果你想訪問styles.rowColor,你需要定義一個styles對象:

const styles = { 
    rowColor: color 
}; 
+0

我的'styles'在'styles.css'中定義,然後我將樣式導入到js文件中。 – user3802348

+0

我現在試着這個'',但得到錯誤「無法讀取未定義的道具」 – user3802348

+0

從該className的開頭刪除'styles',你應該沒有任何錯誤。 'this.props.color'。感謝您澄清'樣式'變量! –