【问题标题】:Overriding react components styles with styled component使用样式化组件覆盖反应组件样式
【发布时间】:2018-08-16 07:37:37
【问题描述】:

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

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

下面是sn-p的代码

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 可能有用

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    您必须手动将 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;
    `;
    

    注意

    请仔细考虑是否在不需要时将您自己的组件包装在样式化组件中。您将禁用 props 的自动白名单,并反转样式组件和结构组件的推荐顺序。

    查看更多信息here

    【讨论】:

    【解决方案2】:
    <label style={{color: "green"}}>{this.props.children}</label>
    

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

    【讨论】:

    • 有人能解释一下为什么这不是正确的答案吗?
    • @YigitAlparslan 人们倾向于使用 styled-component 而不是使用 inline-style 来保持组件干净,所以答案不相关。
    猜你喜欢
    • 2021-11-01
    • 2021-08-24
    • 2020-10-16
    • 1970-01-01
    • 2020-10-27
    • 2021-08-02
    • 2020-07-21
    • 2018-06-27
    • 2019-01-07
    相关资源
    最近更新 更多