簡體   English   中英

使用 Javascript 根據單元格值設置材料 UI 表單元格背景顏色?

[英]Set Material UI Table cell background colour based on cell value using Javascript?

這可能是一個基本問題,但我無法理解它。 我正在使用 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>
  );
}

我為 StyledTableCell 創建了一個新文件並定義了 styles。 請注意,您可以使用 makeStyles 中的道具來更改 styles 依賴於道具。 有關更多信息,請參見此處

此外,您可以通過 classes 屬性將根 class 傳遞給 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM