如何在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 theclassesobject. Template literals inside brackets let us build the property name string on the fly. - Simplified
getRAGFunction: Swapped the longifcondition for aSetto make valid status checks cleaner and easier to update later. - Fallback Style: Added a
ragUclass to handle invalid or missingragStatusvalues—this ensures your chip always has a background color instead of falling back to default styles. - Missing Import: Added the
Chipimport 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
相关产品推荐
相关产品推荐

