[英]if statement inside styled component
export enum SizeEnum {
Small,
Large
}
export interface ICheckbox {
Size: SizeEnum;
}
const Box = styled.div`
height: 20px;
width: 20px;
`
在上面的代码中,我希望能够根据道具有条件地更改<Box>
的高度和宽度值。 我该怎么做?
有关更多信息,请参阅Logical Operators
和Adapting 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.
另一种方法是,如果你想添加几个 css 样式。
const Box = styled.div`
height:100px;
width:100px;
${props => props.Size === 'Small' && css`
height:20px;
width:20px;
`}
`
您可以使用三元运算符
const Box = styled.div`
height: ${props => props.Size === 'Small' ? '20px' : '40px'}
width: ${props => props.Size === 'Small' ? '20px' : '40px'}
`
您可以像这样使用elvis 运算符:
${(props) => props.someValue ? css` width: 20px;` : css` width: 100px; `}
希望这有助于有人研究如何在React 样式组件中使用逻辑运算符。
我们可以像jsx
一样添加 if-checks
const Box = styled.div`
height:100px;
width:100px;
${props => props.Size === 'Small' && `
height:20px;
width:20px;
`}
`
注意:不需要包含css
这个词
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.