简体   繁体   中英

How to make Styled components generic to receive parameters?

I'm trying to use Styled Components with React FC. I want to display few details inside a div container, which all has the same stylings. Instead of writing hard coded such as Name: Height: Weight: etc. in the h-tags, can I do it in a more generic way to pass the text as parameter?

This is the way I have implemented, but I am thinking there should be some better way to do it. Like giving a parameter to the Styled component.

const CardContentContainer= styled.div`
  margin: 4px;
  padding: 4px;
  text-align: left;
  font-size: 14px;
`;

const CardContentDetails = styled.h3`
  font-weight: normal;
  color: #fff;
  margin: 8px;
  white-space: nowrap;
`;

this is the code inside the return:

return (

 <CardContentContainer>
    <CardContentDetails>
      Name: {ItemDetails?.name}
    </CardContentDetails>
    <CardContentDetails>
      Height:{ItemDetails?.height}
    </CardContentDetails>
    <CardContentDetails>
      Weight:{ItemDetails?.weight}
    </CardContentDetails>
  </CardContentContainer>
);

You cant pass such props to Styled components because the main point of SC is to apply a custom style to that component. To make it receive some custom props, you have to wrap it inside another component like so...


const StyledTextField = styled(TextField)`
  margin-bottom: 1rem;
  width: 20em;
`;

const Comp: React.FC<{ title: string }> = ({ title }) => (
  <StyledTextField>{title}</StyledTextField>
);

return (
  <Comp titile="some title" />

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