首页 > 解决方案 > Styled Components / React - 外部元素的样式

问题描述

我正在使用Material UI组件和MaterialTable,我想使用StyledComponents对组件进行时尚化

但是当我尝试使用 StyledComponents 应用样式时,我没有得到想要的结果

CodeSandBox 在线示例

例子:

import styled from 'styled-components'
import MaterialTable from "material-table";

export const MaterialTableStyled = styled(MaterialTable)`
    /* STYLE FOR FILTER ROW */
    tbody > .MuiTableRow-root:first-child {
        background-color: #F1F3F4 !important;
    }
`

当我使用MaterialTableStyled组件时没有应用样式。

相反,如果我div在 StyledComponent 上使用 a:

import styled from 'styled-components'

export const MaterialTableStyled = styled.div`
    /* STYLE FOR FILTER ROW */
    tbody > .MuiTableRow-root:first-child {
        background-color: #F1F3F4 !important;
    }
`

我的自定义样式以这种方式完美地工作:

<MaterialTableStyled> // DIV WITH STYLES
    <MaterialTable
        // ALL PROPS AND STUFFS
    />
</MaterialTableStyled>

...问题是:有可能“覆盖”或更改样式而不使用div更改样式?

标签: javascriptcssreactjsstyled-components

解决方案


组件必须将 className 属性传递给它们的子组件才能使样式化功能起作用。

快速浏览一下,MaterialTable 并没有这样做,因此样式化的组件无法将另一个 css 类分配给表。

与样式化功能兼容的组件

const StyledFriendlyComp = ({className}) => <div className={className}>Styles being applied</div>

不适用于样式化函数的组件

const StyledFriendlyComp = () => <div>Styles not working</div>

在这种情况下,您需要使用另一个元素(如 div)来包装组件。


推荐阅读