【问题标题】:Passing in parameter to Styled Components将参数传递给样式化组件
【发布时间】:2019-05-17 00:30:47
【问题描述】:

如何将参数传递给样式化组件?

我尝试的是创建一个界面和一个样式化的组件:

export interface StyledContainerProps {
  topValue?: number;
}

export const StyledContainer: StyledComponentClass<StyledContainerProps> = styled.div`
  position: absolute;
  top: `${props.topValue || 0}px`;
`;

那我想这样用:

<StyledContainer 
  topValue={123}
>
   This has a distance of 123px to the top
</StyledContainer>

但它是说props 没有topValue 属性。

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    假设您有一个名为 Avatar 的组件,您需要传递一个布尔属性来决定组件的大小(40 或 80 像素)。

    你定义样式组件如下:

    export const UserAvatar = styled(Avatar)`
       height: ${props => (props.large ? 80 : 40)}px;
       width:  ${props => (props.large ? 80 : 40)}px;
    `;
    

    然后你像这样使用它:&lt;UserAvatar large="true" /&gt;

    【讨论】:

      【解决方案2】:

      您可以使用 Typescript 传递参数,如下所示:

      <StyledPaper open={open} />    
      
      ...
      
      const StyledPaper = styled(Paper)<{ open: boolean }>`
         top: ${p => (p.open ? 0 : 100)}%;
      `;
      

      【讨论】:

      • Paper 类型让我觉得这有点令人困惑,如果你只是将 Paper 替换为 div 会起作用吗?
      • 我故意使用Paper 来制作一个带有自定义组件的示例。如果您使用styled.div&lt;{ open: boolean }&gt; 代替div,它会起作用吗?
      【解决方案3】:

      实际上你应该收到cannot read property 'topValue' of undefined 错误。

      使用 insead 函数:

      top: ${({ topValue = 0 }) => topValue}px;
      

      还有一点好处 - 如果 topValue 不存在,您可以使用参数解构并为其分配一个默认值(在您的特定情况下 - 默认值为 0)。

      但是,如果您想在 topValue 为假的所有情况下分配 0,请使用:

      top: ${(props) => props.topValue || 0}px;
      

      注意:双引号是多余的。

      【讨论】:

      • 自定义值123似乎没有通过,但默认值被接受了。
      • @thadeuszlay 实际上是不可能的 :) 如果它不适合您,请使用 ||
      猜你喜欢
      • 2019-04-30
      • 2019-07-25
      • 2016-12-24
      • 2020-10-28
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2020-09-28
      相关资源
      最近更新 更多