MUI5 sx属性扩展样式顺序异常问题咨询:为何与MUI4 makeStyles表现不同?
Let me break down exactly what's happening here—it all boils down to how MUI 5's sx prop handles style caching under the hood.
First, the sx prop relies on Emotion (the styling library MUI 5 uses) to process and generate CSS. Emotion uses a hashing system to avoid redundant CSS: if two style objects end up being structurally identical (same keys and values), it will reuse the same CSS class instead of generating a new one.
Let's look at your code specifically:
- In your original setup, the
elsebranch usessx={{...styles.red, ...styles.green}}. When you spread these objects, thecolor: 'green'fromstyles.greenoverwritescolor: 'red'fromstyles.red, so the final style object is{ color: 'green' }. - The even-index branch uses
sx={{...styles.red}}, which resolves to{ color: 'red' }.
Since these are two distinct style objects, Emotion generates two separate CSS classes—one for red, one for green—so your items display correctly.
But when you flip the spread order in the else branch to sx={{...styles.green, ...styles.red}}:
- Now,
color: 'red'fromstyles.redoverwritescolor: 'green'fromstyles.green, making the final style object{ color: 'red' }. - This is exactly identical to the style object used for even-index items.
Emotion detects that both branches are requesting the same style rules, so it reuses the same CSS class for all items. That's why everything ends up red—there's no longer a unique class for green styles.
Your console.log showing the styles object hasn't changed makes sense: the original styles are untouched. The only thing that changed is the order of spreading, which altered the final merged style object to match the even branch's style.
Just a quick note: While you're exploring workarounds from MUI 4, a cleaner way to handle this parity-based styling with sx would be to inline the condition directly:
<Typography sx={{ color: index % 2 === 0 ? 'red' : 'green' }}> {item} </Typography>
This avoids any confusion around object spreading and caching entirely.
内容的提问来源于stack exchange,提问作者Anastasia Posmashna

