Overriding react components styles with styled component

余生长醉 提交于 2020-08-07 05:07:43

问题


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.

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.

Below is snippet of code

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>

Please refer the link on codesandbox which might be useful


回答1:


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

NOTE:

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.

See more info here.




回答2:


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

or

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


来源:https://stackoverflow.com/questions/51871930/overriding-react-components-styles-with-styled-component

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