css - MUI - 如何在特定样式的组件中使用伪类

标签 css reactjs material-ui css-selectors styled-components

我对整个 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>

最佳答案

ItemGrid 的直接子级,因此您可以使用 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>

Codesandbox Demo

关于css - MUI - 如何在特定样式的组件中使用伪类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69742570/

相关文章:

javascript - 通过 UI 过滤 JSON 对象数组

javascript - 如何在 ES2015 类方法中访问类和调用对象?

css - 如何编辑特定页面的 html/css?

css - 如何使用 CSS 编写带有圆 Angular 和阴影的 3 边框(无左侧)?

javascript - 列表项不会因打开辅助功能而改变高度以响应大文本

reactjs - 如何在 react-navigation v5 中从单个屏幕隐藏堆栈导航标题

css - 部署后不会反射(reflect) CSS 文件中的更改

php - 了解 woocommerce 主题 - 使用我自己的主题

javascript - 如何在 Material UI 选择菜单中使用子标题

reactjs - 如何在网格容器中将 TextField 扩展到全宽?