如何生成具有不同颜色行的 React table?

How to generate React table with different colored rows?

我正在尝试创建一个 React table,其中每一行要么是灰色要么是白色。我通过在创建时将道具“灰色”或“白色”传递给行来做到这一点,但在我的 MyRow class 中,我不确定如何使用这个道具并将其转换为样式。

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;
}

我相信您应该能够将 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
};

按照此操作使用 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>
  ),
},