样式化组件 / React - 外部元素的样式

IT技术 javascript css reactjs styled-components
2021-05-06 00:40:46

我正在使用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来更改样式?

1个回答

组件必须将 className 属性传递给它们的子组件,才能使样式化的函数工作。

乍一看,MaterialTable 并没有这样做,因此样式化组件无法将另一个 css 类分配给表格。

与样式函数兼容的组件

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

不适用于样式函数的组件

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

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