简体   繁体   English

样式组件内的 if 语句

[英]if statement inside styled component

export enum SizeEnum {
    Small,
    Large
}

export interface ICheckbox {
    Size: SizeEnum;
}

const Box = styled.div`
    height: 20px;
    width: 20px;
`

In the above code I want to be able to conditionally change the height and width value of <Box> based on the prop.在上面的代码中,我希望能够根据道具有条件地更改<Box>的高度和宽度值。 How do I do this?我该怎么做?

See Logical Operators and Adapting based on props for more info.有关更多信息,请参阅Logical OperatorsAdapting based on props

// Box.
const Box = styled.div`

  height: ${({Size}) => 
    Size === 'Small' && '25px' ||
    Size === 'Large' && '100px' || 
    '50px'
  };

  width: ${({Size}) => 
    Size === 'Small' && '25px' || 
    Size === 'Large' && '100px' || 
    '50px'
  };

`

// Render.
<Box/> // 50px - Normal.
<Box Size="Small"/> // 25px - Small.
<Box Size="Large"/> // 100px - Large.

Another way to do this, if you want to add several css styles.另一种方法是,如果你想添加几个 css 样式。

const Box = styled.div`
    height:100px;
    width:100px;
    ${props => props.Size === 'Small' && css`
         height:20px;
         width:20px;
    `}
`

You can use the ternary operator您可以使用三元运算符

const Box = styled.div`
height: ${props => props.Size === 'Small' ? '20px' : '40px'}
width: ${props => props.Size === 'Small' ? '20px' : '40px'}
`

Reference: https://www.styled-components.com/docs/basics参考: https : //www.styled-components.com/docs/basics

You can use the elvis operator in something like this:您可以像这样使用elvis 运算符

${(props) => props.someValue ? css` width: 20px;` : css` width: 100px; `}

Hope this helps someone looking into how to use logical operators in React styled components .希望这有助于有人研究如何在React 样式组件中使用逻辑运算符

We can add the if-checks just like jsx我们可以像jsx一样添加 if-checks

const Box = styled.div`
    height:100px;
    width:100px;
    ${props => props.Size === 'Small' && `
         height:20px;
         width:20px;
    `}
` 

Note: No need to include the word css注意:不需要包含css这个词

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

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