[英]styled-components not applying style to custom functional react component
When using styled-components
to style a custom functional react component, the styles are not being applied.当使用
styled-components
为自定义功能性反应组件设置样式时,不会应用这些样式。 Here is a simple example where the styles are not being applied to the StyledDiv
:这是一个简单的示例,其中样式未应用于
StyledDiv
:
const Div = () => (<div>test</div>)
const StyledDiv = styled(Div)`
color: red;
`;
What is the best way to make sure that the styles get applied correctly?确保正确应用样式的最佳方法是什么?
The styled method works perfectly on all of your own or any third-party components as well, as long as they pass the className prop to their rendered sub-components, which should pass it too, and so on.
样式化的方法可以完美地在您自己的所有第三方组件上运行,也可以在任何第三方组件上完美运行,只要它们将className prop传递给其呈现的子组件,子组件也应该通过它,依此类推。 Ultimately, the className must be passed down the line to an actual DOM node for the styling to take any effect.
最终,必须将className向下传递到实际的DOM节点,以使样式生效。
For example, your component would become: 例如,您的组件将变为:
const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
color: green;
`;
Modified example: 修改示例:
const styled = styled.default const Div = ({ className }) => (<div className={className}>test</div>) const StyledDiv = styled(Div)` color: green; font-size: larger; `; const App = () => { return(<StyledDiv>Test</StyledDiv>) } ReactDOM.render(<App />, document.querySelector('.app'))
<script src="//unpkg.com/react@16.5.2/umd/react.development.js"></script> <script src="//unpkg.com/react-dom@16.5.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/3.4.9/styled-components.min.js"></script> <div class="app"></div>
Using styled(Component)
like that creates a class which is passed as a prop called className
to the wrapped component. 像这样使用
styled(Component)
创建一个类,该类作为名为className
的prop传递给包装的组件。
You can then apply that to the root element: 然后可以将其应用于根元素:
const Div = ({ className }) => (
<div className={className}>test</div>
)
const StyledDiv = styled(Div)`
color: red;
`;
In case you cannot change the original component (it's imported or generated), let's assume that component is a <span>
, you may wrap it with eg a <div>
and nest the css rules, like so: 如果您不能更改原始组件(导入或生成),则假定该组件为
<span>
,可以将其包装为例如<div>
并嵌套css规则,如下所示:
const ComponentICantTouchWrapper = ({className}) => (
<div className={className}><ComponentICantTouch /></div>
);
const StyledComponentICantTouch = styled(ComponentICantTouchWrapper)`
> span {
color: red;
}
`;
In my case, I was trying to use styled components with material UI.就我而言,我试图使用带有材质 UI 的样式组件。 The thought I had was to do this: (it worked in most cases)
我的想法是这样做:(在大多数情况下都有效)
const StyledTableRow = ({ className, children }) => (
<TableRow className={className}>{children}</TableRow>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.