我对整个 React 和 MUI 风格的组件很陌生。现在我正在开发一个网格,我想为特定组件的所有子组件设置样式。我想做的是 ${Item1}:nth-child(3n-1)
, ${Item2}:nth-child(3n-1)
, ${Item3}:nth-child(3n-1)
但它不能像这样工作:
const Grid = styled('div')(({ theme }) => ({
width: '100%',
height: '100%',
padding: 0,
display: 'grid',
gap: 0,
gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
`${Item1}:nth-child(3n-1)`: {
backgroundColor: 'lightYellow'
},
gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
`${Item2}:nth-child(3n-1)`: {
backgroundColor: 'lightGreen'
},
gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
`${Item3}:nth-child(3n-1)`: {
backgroundColor: 'lightBlue'
}
}
const Item1 = styled('div')(({ theme }) => ({
...
}));
const Item2 = styled('div')(({ theme }) => ({
...
}));
const Item3 = styled('div')(({ theme }) => ({
...
}));
<Grid>
<Item1 />
<Item2 />
<Item3 />
<Item1 />
<Item2 />
<Item3 />
<Item1 />
<Item2 />
<Item3 />
<Grid>
最佳答案
Item
是 Grid
的直接子级,因此您可以使用 div > div
选择器:
const Grid = styled('div')(({ theme }) => ({
...,
'& > :nth-child(3n-2)': {
backgroundColor: 'lightYellow',
},
'& > :nth-child(3n-1)': {
backgroundColor: 'lightGreen',
},
'& > :nth-child(3n)': {
backgroundColor: 'lightBlue',
},
}));
如果您想定位特定的子级,可以添加类名来标识它:
const Grid = styled('div')(({ theme }) => ({
...,
'& > .item1': {
backgroundColor: 'lightYellow',
},
'& > .item2': {
backgroundColor: 'lightGreen',
},
'& > .item3': {
backgroundColor: 'lightBlue',
},
}));
<Grid>
<Item className="item1" />
<Item className="item2" />
<Item className="item3" />
<Item className="item1" />
<Item className="item2" />
<Item className="item3" />
<Item className="item1" />
<Item className="item2" />
<Item className="item3" />
</Grid>
关于css - MUI - 如何在特定样式的组件中使用伪类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69742570/