使用样式组件覆盖反应组件样式 [英] Overriding react components styles with styled component
问题描述
我试图覆盖通过样式组件(styled.)的标准方式创建的组件样式,并且两种方式(styled()
和 style.extends
)都有效为了我.
I tried to override style of component created by standard way of styled-components(styled.) and both the ways(styled()
and style.extends
) worked for me.
但是当我尝试使用 styled()
方法覆盖简单反应组件的样式时,它会呈现组件但不会覆盖它的样式.
But when I am trying to override style of simple react component with styled()
approach, its rendering the component but not overriding it's style.
下面是代码片段
import React, { Component } from "react";
import styled from "styled-components";
export default class MyLabel extends Component {
render() {
return <label>{this.props.children}</label>;
}
}
const StyledMyLabel = styled(MyLabel)`
color: green;
`;
为了显示目的,我使用以下语法
And for display purpose I am using following syntax
<StyledMyLabel>My Styled Label</StyledMyLabel>
请参考可能有用的 codeandbox 上的链接
推荐答案
您必须手动将 className
传递给所需的样式元素才能使其工作.
You have to pass className
to desirable styling element manually to make it works.
import React, { Component } from "react";
import styled from "styled-components";
export default class MyLabel extends Component {
render() {
return <label className={this.props.className}>{this.props.children}</label>;
}
}
const StyledMyLabel = styled(MyLabel)`
color: green;
`;
注意:
仔细考虑是否在不需要时将自己的组件包装在样式组件中.您将禁用 props 的自动白名单,并反转样式组件和结构组件的推荐顺序.
Consider carefully whether to wrap your own components in a styled component, when it isn't necessary. You will disable the automatic whitelisting of props, and reverse the recommended order of styled components and structural components.
在此处查看更多信息.
这篇关于使用样式组件覆盖反应组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!