首页 > 解决方案 > 使用Javascript根据单元格值设置Material UI Table单元格背景颜色?

问题描述

这可能是一个基本问题,但我无法理解它。我正在使用 React 和 JS,并希望根据单元格的值更改“Charge Left”单元格的背景。EG 如果电量 < 30 背景为红色,如果电量为 31 - 59 背景为橙色,如果电量 > 59 背景为绿色。

我在 JS 中尝试了多种不同的解决方案,但我根本无法让它工作。

<StyledTableCell align="center">{user.chargeLeft}</StyledTableCell>

import React, { useEffect, useState } from "react";
import "./App.css";
import "./colorChange.jsx";
import Amplify, { API, graphqlOperation } from "aws-amplify";
import awsconfig from "./aws-exports";
import { AmplifySignOut, withAuthenticator } from "@aws-amplify/ui-react";
import { listChargeProfiles } from "./graphql/queries";

import logo from "./evslogo.png";

import { Paper } from "@material-ui/core";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";

Amplify.configure(awsconfig);

function App() {
  const StyledTableCell = withStyles(theme => ({
    head: {
      backgroundColor: theme.palette.common.black,
      color: theme.palette.common.white,
      fontSize: 18,
      fontWeight: "bold"
    },
    body: {
      fontSize: 16
    }
  }))(TableCell);

  const StyledTableRow = withStyles(theme => ({
    root: {
      "&:nth-of-type(odd)": {
        backgroundColor: theme.palette.action.hover
      }
    }
  }))(TableRow);

  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUserData();
  }, []);

  const fetchUserData = async () => {
    try {
      const userData = await API.graphql(graphqlOperation(listChargeProfiles));
      const userList = userData.data.listChargeProfiles.items;
      setUsers(userList);
    } catch (error) {
      console.log("Failed to Return Users.", error);
    }
  };

  const useStyles = makeStyles({
    table: {
      minWidth: 700
    }
  });

  const classes = useStyles();

  return (
    <div className="App">
      <header className="evs-header">
        <div className="container">
          {/* EVS Logo */}
          <img src={logo} alt="Evs Energy Logo" className="logoEvs" />
          <div className="vertical-divider"></div>
          <p className="charge-text">
            Charging <br />
            Profile
          </p>
        </div>
        <AmplifySignOut />
      </header>
      {/* Page Divider */}
      <div className="evs-header-bar"></div>
      <TableContainer component={Paper}>
        <Table className={classes.table} aria-label="customized table">
          <TableHead>
            <TableRow>
              <StyledTableCell align="center">First Name</StyledTableCell>
              <StyledTableCell align="center">Last Name</StyledTableCell>
              <StyledTableCell align="center">Email</StyledTableCell>
              <StyledTableCell align="center">Car Model</StyledTableCell>
              <StyledTableCell align="center">Charge Level</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {users.map(user => (
              <StyledTableRow>
                <StyledTableCell align="center">
                  {user.firstName}
                </StyledTableCell>
                <StyledTableCell align="center">
                  {user.lastName}
                </StyledTableCell>
                <StyledTableCell align="center">{user.email}</StyledTableCell>
                <StyledTableCell align="center">
                  {user.carModel}
                </StyledTableCell>
                <StyledTableCell align="center">
                  {user.chargeLeft}
                </StyledTableCell>
              </StyledTableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Footer Section */}
      <footer className="evs-footer">
        <div className="container">
          <p className="footer-text">About</p>
          <p className="footer-text">Help Centre</p>
        </div>
      </footer>
    </div>
    // </div>
  );
}

标签: javascriptcssreactjsmaterial-uireact-table

解决方案


我为 StyledTableCell 创建了一个新文件并定义了样式。请注意,您可以使用 makeStyles 中的道具来更改依赖于道具的样式。有关更多信息,请参见此处

此外,您可以通过 classes 属性将根类传递给 TableCell。

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TableCell from "@material-ui/core/TableCell";

const useStyles = makeStyles((theme) => ({
  root: {
    background: (props) => {
      if (props.charge <= 30) {
        return "blue";
      } else if (props.charge >= 31 && props.charge <= 59) {
        return "orange";
      }
      else {
        //props.charge > 5
        return "green";
      }
    },
  },
}));
const StyledTableCell = (props) => {
  const classes = useStyles2(props);
  return (
    <TableCell
      classes={{
        root: classes.root,
      }}
    >
      {props.children}
    </TableCell>
  );
};

export default StyledTableCell;

然后,在您的主文件中,您会将 Charge 道具传递给您的新组件:

...
import StyledTableCell from "./StyledTableCell";

...
<StyledTableCell align="center" charge={user.chargeLeft}>
    {user.chargeLeft}
</StyledTableCell>


推荐阅读