【问题标题】:How to generate React table with different colored rows?如何生成具有不同颜色行的 React 表?
【发布时间】: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 作为道具传递,那么只需执行 &lt;tr className={rowColor}&gt;。你为什么要通过另一个名为styles 的对象来传递rowColorstyles 在哪里定义?它不包含在您的代码中。

标签: javascript css reactjs styling


【解决方案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
};

【讨论】:

  • 我的styles是在styles.css中定义的,然后我将样式导入到js文件中。
  • 我现在正在尝试这个&lt;tr className={styles.this.props.color}&gt;,但收到错误“无法读取未定义的道具”
  • 从该类名的开头删除styles,您应该不会收到任何错误。 this.props.color。感谢您对 styles 变量的澄清!
  • 嗯,但是我将如何指定在 styles 文件中查找灰色或白色? this.props.color 只是指向“灰色”或“白色”,它们没有在 js 文件中定义,而是由 styles.gray/styles.white 访问
  • 您的问题/上面的代码 sn-ps 中缺少的部分似乎是样式 js 文件。从您最初的问题来看,样式/类名似乎只是与发布的 CSS 文件相关联。如果没有,请提供该样式文件。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2022-12-04
    • 2010-10-03
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多