首页 > 解决方案 > 如何根据单元格中的值更改表格中的背景(反应)

问题描述

表格组件从父级接收数据并组织它们。检索表后,再次用数据填充表。

如何根据其中的值更改每个单元格的背景(使用 css 样式?)

import React from 'react';
import '../layouts/table.css'

const Table = (props) => {

    let data = props.data

    let table = [
        ["city", "so2", "no2", "pm25", "pm10", "o3", "co"],
        ["2", "150", "1", "2", "5", "9", "10"],
        ["2", "250", "1", "2", "5", "9", "10"],
        ["2", "350", "1", "2", "5", "9", "10"],
        ["2", "450", "1", "2", "5", "9", "10"],
        ["2", "2", "1", "2", "5", "9", "10"],
        ["2", "10", "1", "2", "5", "9", "10"],
        ["2", "10", "1", "2", "5", "9", "10"],
        ["2", "10", "1", "2", "5", "9", "10"],
        ["2", "0", "1", "2", "5", "9", "10"],
    ]

    for (let i = 0; i < data.length; i++) {
         //organizes the data and places it in the table
    }

    const row = table.map((table) =>
        <tr>
            <td scope="row" key={table[0][0]}>{table[0]}</td>
            <td id="so2" className="">{table[1]}</td>
            <td id="no2" className="">{table[2]}</td>
            <td id="pm24" className="">{table[3]}</td>
            <td id="pm10" className="">{table[4]}</td>
            <td id="o3" className="">{table[5]}</td>
            <td id="co" className="">{table[6]}</td>
        </tr>
    )

    return (

        <table id="table" className="table table-striped text-center">
            <thead className="table-primary">

                <tr>
                    <th scope="col">city</th>
                    <th scope="col">so2</th>
                    <th scope="col">no2</th>
                    <th scope="col">pm25</th>
                    <th scope="col">pm10</th>
                    <th scope="col">o3</th>
                    <th scope="col">co</th>
                </tr>

            </thead>
            <tbody>

                {row}

            </tbody>
        </table>
    );
}

export default Table;

标签: javascriptreactjs

解决方案


您可以使用以下内容:

const row = table.map((table) =>
    <tr>
        <td scope="row" key={table[0][0]}>{table[0]}</td>
        <td id="so2" style={{ color: table[1] != "soe2" ? 'blue': 'green'}}>{table[1]}</td>
        <td id="no2" style={{ color: table[2] != "soe2" ? 'blue': 'green'}}>{table[2]}</td>
        <td id="pm24" style={{ color: table[3] != "soe2" ? 'blue': 'green'}}>{table[3]}</td>
        <td id="pm10" style={{ color: table[4] != "soe2" ? 'blue': 'green'}}>{table[4]}</td>
        <td id="o3" style={{ color: table[5] != "soe2" ? 'blue': 'green'}}>{table[5]}</td>
        <td id="co" style={{ color: table[6] != "soe2" ? 'blue': 'green'}}>{table[6]}</td>
    </tr>
)

推荐阅读