简体   繁体   English

如何使样式化组件通用以接收参数?

[英]How to make Styled components generic to receive parameters?

I'm trying to use Styled Components with React FC.我正在尝试将样式组件与 React FC 一起使用。 I want to display few details inside a div container, which all has the same stylings.我想在 div 容器中显示一些细节,它们都具有相同的样式。 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?不是在 h 标签中编写硬编码,例如 Name: Height: Weight: 等,我可以用更通用的方式将文本作为参数传递吗?

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.就像给 Styled 组件一个参数一样。

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.您不能将此类道具传递给 Styled 组件,因为 SC 的要点是将自定义样式应用于该组件。 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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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