如何在Styled-Components中实现多props组合条件判断生成对应CSS样式
styled-components多条件prop样式判断实现方案
你编写的代码不符合语法规范的核心原因是多条件判断表达式和后面的css代码块之间缺少&&逻辑与运算符连接,补上运算符即可实现多条件同时校验的需求:
const Box = styled.div` ${({ someProp, someOtherProp }) => // 多条件判断后加 && 连接css代码块 someProp && !someOtherProp && css` border: 1px solid red; `}; `
styled-components的模板语法支持传入任意JS表达式,只要最终返回css工具函数生成的样式对象、CSS字符串、或者null即可,所有原生JS支持的条件判断语法都可以直接使用。如果是更复杂的多分支判断场景,推荐使用三元运算符或者函数块+if判断的写法,可读性更高:
多分支判断写法示例
三元运算符实现
const Box = styled.div` ${({ type, disabled }) => disabled ? css` opacity: 0.5; cursor: not-allowed; ` : type === 'primary' ? css` background: #1677ff; color: #fff; ` : type === 'danger' ? css` background: #ff4d4f; color: #fff; ` : css` background: #fff; border: 1px solid #d9d9d9; `} `
函数块+if判断实现
适合逻辑特别复杂的场景,支持任意数量的分支判断:
const Box = styled.div` ${({ someProp, someOtherProp, type }) => { // 多条件同时满足 if (someProp && !someOtherProp) { return css` border: 1px solid red; ` } // 其他分支判断 if (type === 'primary') { return css` background: #1677ff; ` } // 不满足所有条件时返回null即可 return null }} `
内容的提问来源于stack exchange,提问作者Eric Nguyen
相关产品推荐
相关产品推荐

