用带样式的组件覆盖反应组件样式

Overriding react components styles with styled component

我试图覆盖由标准方式 styled-components(styled.) 创建的组件样式,这两种方式(styled()style.extends)对我都有效。

但是当我尝试使用 styled() 方法覆盖简单反应组件的样式时,它会渲染组件但不会覆盖它的样式。

下面是代码片段

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

出于显示目的,我使用了以下语法

<StyledMyLabel>My Styled Label</StyledMyLabel>

请参考可能有用的link on codesandbox

<label style={{color: "green"}}>{this.props.children}</label>

const style = {color : "green"};
<label style={style}>{this.props.children}</label>

您必须手动将 className 传递给所需的样式元素才能使其生效。

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

注意

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.

查看更多信息here