Styled Components / React - Style on external element

房东的猫 提交于 2019-12-11 07:48:02

问题


I'm using Material UI components and MaterialTable and I want to stylish the components using StyledComponents

But I not been having the desired results when I try to apply styles using StyledComponents

CodeSandBox Online Example

Example:

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;
    }
`

When I use the MaterialTableStyled component no applied the style.

Instead, if I use a div on my StyledComponent:

import styled from 'styled-components'

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

My custom styles work perfecty on that way:

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

...the question is: it's possible "override" or change styles without using the div to change the style?


回答1:


A component has to pass the className property into their children in order styled function to work.

From a quick look, MaterialTable doesn't do that, as a result styled components can't assign another css class to the table.

Component compatible with styled function

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

Component that won't work with styled function

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

In this cases you need to wrap the component with another element like div.



来源:https://stackoverflow.com/questions/57499833/styled-components-react-style-on-external-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!