简体   繁体   中英

Extending styles with styled-components not working

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!

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, or any custom component
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-component

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>
)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM