代码之家  ›  专栏  ›  技术社区  ›  user3802348

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

  •  2
  • user3802348  · 技术社区  · 8 年前

    我试图创建一个React表,其中的每一行要么是灰色的,要么是白色的。我是通过在创建道具时传递灰色或白色的道具行来实现的,但在我的MyRow类中,我不确定如何将这个道具转换为一种样式。

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

    我的行。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>
        );
    }
    

    .td {
        font-weight: 500;
        padding: 0 20px;
    }
    
    .gray {
        background-color: #d3d3d3;
    }
    
    .white {
        background-color: #fff;
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   ghost_dad    8 年前

    我认为您应该能够按如下方式将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 ,您需要一个 对象定义:

    const styles = {
        rowColor: color
    };
    
        2
  •  0
  •   Praveen    4 年前

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