将参数传递给样式化组件

Passing in parameter to Styled Components

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

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

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

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

改用函数:

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

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

然而,如果你想在 topValue 为假的每种情况下分配 0,请使用:

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

注意:双反引号是多余的。

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

<StyledPaper open={open} />    

...

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

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

您定义样式组件如下:

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

你可以这样使用它:<UserAvatar large="true" />