【问题标题】:MUI - How to use pseudo class in specific styled componentMUI - 如何在特定样式的组件中使用伪类
【发布时间】:2021-12-12 23:25:15
【问题描述】:

我不熟悉整个 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>

【问题讨论】:

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


    【解决方案1】:

    ItemGrid 的直接子代,因此您可以使用div &gt; 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>
    

    【讨论】:

    • 好的,如何设置 Item2 和 Item3?
    • @Teamol 你可以使用&amp; &gt; :nth-child(3n - 1)&amp; &gt; :nth-child(3n) 来选择每一行的第二和第三项。
    • 类名css-16kb41是由情感生成的,如果你想针对特定的comp,像我的第二种方法一样添加你的自定义类名。
    • 是的,你是对的,我没看到,谢谢。
    猜你喜欢
    • 2022-01-08
    • 2018-12-24
    • 2022-10-23
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2022-11-19
    • 2022-08-16
    • 2021-09-19
    相关资源
    最近更新 更多