【发布时间】:2016-07-15 16:12:27
【问题描述】:
我正在尝试创建一个 React 表,其中每一行都是灰色或白色的。我通过在创建道具时传递“灰色”或“白色”道具来做到这一点,但在我的 MyRow 课程中,我不确定如何获取此道具并将其转换为样式。
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;
}
【问题讨论】:
-
如果您已经定义了 CSS 类,并且您将
className作为道具传递,那么只需执行<tr className={rowColor}>。你为什么要通过另一个名为styles的对象来传递rowColor。styles在哪里定义?它不包含在您的代码中。
标签: javascript css reactjs styling