[英]How to generate React table with different colored rows?
I'm trying to create a React table in which each row is either gray or white.我正在尝试创建一个 React 表,其中每一行都是灰色或白色。 I am doing this by passing rows the props 'gray' or 'white' upon their creation, but in my MyRow class I'm not sure how to take this prop and convert it to a style.
我通过在创建时传递道具“灰色”或“白色”来做到这一点,但在我的 MyRow 类中,我不确定如何使用这个道具并将其转换为样式。
Relevant code in MyTable.js: 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 function: 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: MyRow.css:
.td {
font-weight: 500;
padding: 0 20px;
}
.gray {
background-color: #d3d3d3;
}
.white {
background-color: #fff;
}
I believe you should be able to pass the prop directly to the row as follows, since it's already defined as a string in MyTable.js
file:我相信您应该能够将 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>
);
}
Also, from the code you have posted, it's unclear where the styles
object is located where you're trying to access these properties.此外,根据您发布的代码,尚不清楚
styles
对象位于您尝试访问这些属性的位置。 If you wanted to access styles.rowColor
, you would need a styles
object defined:如果您想访问
styles.rowColor
,则需要定义一个styles
对象:
const styles = {
rowColor: color
};
Follow this to change individual row cell color using row.value按照此使用 row.value 更改单个行单元格颜色
{
Header: () => <div className="text-center font-weight-bold">Status</div>,
accessor: "selectedstatus",
className: "font",
width: 140,
Cell: (row) => (
<div
className="text-center h-6"
style={{ background: row.value === "Selected" ? "green" : "red" }}
>
{row.value}
</div>
),
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.