You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Material UI中插入可变类名以实现动态背景色组件?

Fixing Dynamic Class Names for Your React RAG Chip Component

Hey Katie, I see where the issue is with your dynamic class name setup—let's get this sorted out quickly!

The Problem

Your current attempt to build the dynamic class name (${classes.rag ${getRAG(ragStatus)}}) isn't valid JavaScript syntax. When you need to access an object property using a dynamic string, you can't use dot notation; you have to use bracket notation instead.

The Solution

Here's the corrected version of your RAGChip component, with the key fix in the className prop:

import React from 'react';
import { makeStyles, Chip } from '@material-ui/core'; // Don't forget to import Chip!

const useStyles = makeStyles(theme => ({
  ragChip: { padding: 2 },
  ragR: { backgroundColor: theme.palette.error.dark },
  ragA: { backgroundColor: theme.palette.warning.dark },
  ragG: { backgroundColor: theme.palette.success.dark },
  ragU: { backgroundColor: theme.palette.grey[500] }, // Optional: Fallback style for unknown status
}));

const getRAG = ragStatus => {
  if (!ragStatus) return 'U';
  
  const rag = ragStatus.toString().toUpperCase();
  // Simplify valid status checks with a Set
  const validStatuses = new Set(['RED', 'AMBER', 'GREEN', 'R', 'A', 'G']);
  return validStatuses.has(rag) ? rag.charAt(0) : 'U';
};

const RAGChip = ({ ragStatus }) => {
  const classes = useStyles();
  // Use bracket notation to dynamically access the correct class
  const ragClass = classes[`rag${getRAG(ragStatus)}`];
  
  return (
    <Chip 
      size="small" 
      label="" 
      className={`${classes.ragChip} ${ragClass}`} 
    />
  );
};

export default RAGChip;

Key Changes Explained:

  • Dynamic Class Access: Instead of trying to concatenate with dot notation, we use classes[rag${getRAG(ragStatus)}] to dynamically grab the right class from the classes object. Template literals inside brackets let us build the property name string on the fly.
  • Simplified getRAG Function: Swapped the long if condition for a Set to make valid status checks cleaner and easier to update later.
  • Fallback Style: Added a ragU class to handle invalid or missing ragStatus values—this ensures your chip always has a background color instead of falling back to default styles.
  • Missing Import: Added the Chip import from Material-UI (it was missing in your original code, which would have caused a runtime error).

Bonus Tip

To add extra safety and ensure you never use an invalid class, you can add a fallback check:

const ragClass = classes[`rag${getRAG(ragStatus)}`] || classes.ragU;

This guarantees you always get a valid class, even if unexpected values make their way into ragStatus.

内容的提问来源于stack exchange,提问作者Katie7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:42:41