React使用styled-components根据props设置按钮背景色不生效问题咨询
问题原因
- 核心错误是
Button组件样式中的三元判断逻辑语法错误:你写的primary ? ("#007bff" ? secondary : "#242424") : "transparent"中,"#007bff"是永远为真的字符串,所以只要primary属性为true,就会返回secondary属性的布尔值,最终渲染的CSS为background-color: false,自然无法正常显示背景色。 - 现有逻辑仅覆盖了primary、secondary两种状态,没有兼容你预设的info、warning两类背景色。
修复方案
方案1:修正布尔属性判断逻辑,兼容4种预设类型
直接修改GlobalStyles.js中的Button样式定义,修正判断逻辑即可,原有组件调用方式无需改动:
export const Button = styled.button` padding: 8px 20px; background-color: ${({ primary, secondary, info, warning }) => { if (primary) return '#007bff' if (secondary) return '#242424' if (info) return '#17a2b8' if (warning) return '#ffc107' return 'transparent' }}; color: #fff; font-size: 18px; border-radius: 4px; outline: none; border: none; cursor: pointer; white-space: nowrap; &:hover { opacity: 0.9; } `;
后续需要使用info、warning类型的按钮,直接添加对应属性即可,例如<Button warning>警告按钮</Button>。
方案2:使用type属性统一管理(推荐)
如果预设类型较多,使用统一的type属性传递类型会更易维护,修改Button样式定义如下:
export const Button = styled.button` padding: 8px 20px; background-color: ${({ type }) => { switch(type) { case 'primary': return '#007bff' case 'secondary': return '#242424' case 'info': return '#17a2b8' case 'warning': return '#ffc107' default: return 'transparent' } }}; color: #fff; font-size: 18px; border-radius: 4px; outline: none; border: none; cursor: pointer; white-space: nowrap; &:hover { opacity: 0.9; } `;
调用时传入对应type属性即可,示例如下:
<Button type="primary">SIGN UP</Button> <Button type="secondary">SIGN UP</Button> <Button type="info">说明按钮</Button> <Button type="warning">警告按钮</Button>
内容的提问来源于stack exchange,提问作者J.Wujeck
相关产品推荐
相关产品推荐

