传递参数给Styled Components

15

我该如何将参数传递给Styled Components?

我尝试创建了一个接口和一个styled组件:

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属性。

3个回答

20
实际上,你应该收到一个“无法读取未定义的属性'topValue'”的错误。
使用一个函数代替:
const StyledContainer = styled.div<{ topValue: number }>`
    top: ${({ topValue = 0 }) => topValue}px;
`;

还有一个小奖励 - 你可以使用参数解构并为`topValue`分配一个默认值(如果不存在的话 - 在你的特定情况下,该默认值将为`0`)。
然而,如果你想在每种情况下当`topValue`为假值时都赋值为`0`,请使用:
const StyledContainer = styled.div<{ topValue: number }>`
    top: ${(props) => props.topValue || 0}px;
`;

注意:重复使用反引号是多余的。

似乎自定义值 123 没有传递,但默认值被接受了。 - thadeuszlay
@thadeuszlay,实际上这是不可能的 :) 如果对您不起作用,请使用 || - kind user

15

以下是使用Typescript传递参数的方法:

<StyledPaper open={open} />    

...

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

类型Paper让这有点更加混乱,如果你只是用div替换Paper,这会起作用吗? - Sam
5
我特意使用“Paper”作为示例来展示如何使用自定义组件。如果您使用“div”,则可以使用“styled.div<{ open: boolean }>”。 - Jöcker

2

假设您有一个名为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" />

(注:该段内容为关于如何使用it技术中的用户头像组件的说明)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接