Extending styles with styled-components not working

佐手、 提交于 2020-04-10 14:54:53

问题


I'm trying to extend styles for a react component using styled-components but is not working. AFAIK, I'm doing it the right way, but perhaps I'm missing something... Here is what I have:

import React from "react";
import styled from "styled-components";

const TextContainer = ({ text }) => {
  return <p dangerouslySetInnerHTML={{ __html: text }} />;
};

const Paragraph = styled(TextContainer)`
  background: red;
`;

class Home extends React.Component {
  render() {
    const { t } = this.props;
    return <Paragraph text="This is a test" />;
  }
}

export default Home;

Of course, the expected result is to have a red background on p, but right now the output looks like this:

Any idea on how to solve this? Probably I'm missing something, but I can't realize what.

Thanks is advance!


回答1:


As stated in documentation:

The styled method works perfectly on all of your own or any third-party components, as long as they attach the passed className prop to a DOM element.

Example

// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
  color: palevioletred;
  font-weight: bold;
`;

render(
  <div>
    <Link>Unstyled, boring Link</Link>
    <br />
    <StyledLink>Styled, exciting Link</StyledLink>
  </div>
);

Ref: https://www.styled-components.com/docs/basics#styling-any-components




回答2:


I didn't know that was a way to do it. I would do:

    const Link = styled.a`
    ..put you css styles here (className styles)
   `

   const StyledLink = styled(Link) `
      color: palevioletred;
      font-weight: bold;
   `

render(){
return(
<div>
    <Link>Unstyled, boring Link</Link>
    <br />
    <StyledLink>Styled, exciting Link</StyledLink>
  </div>
)
}


来源:https://stackoverflow.com/questions/54113367/extending-styles-with-styled-components-not-working

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