React中如何编写内联else if实现响应式激活按钮样式
解决方案
要实现不同视口下激活按钮的样式切换,可以通过嵌套三元表达式模拟内联else if逻辑,结合媒体查询结果返回对应样式。以下是调整后的代码:
const btnMobileStyle = useMediaQuery('(min-width: 375px)') const btnTabletStyle = useMediaQuery('(min-width: 768px)') // 简化样式定义,直接使用外部的themeColor const styles = { buttonMobile: { borderBottom: `2px solid ${themeColor}`, }, buttonTablet: { borderBottom: 'none', backgroundColor: `${themeColor}`, }, } return ( <main className="main"> <div className="main__btn-container"> <button style={ overviewActive ? btnTabletStyle ? styles.buttonTablet : btnMobileStyle ? styles.buttonMobile : {} : {} } onClick={updateOverview} className="main__btn" > Overview </button> <button style={ structureActive ? btnTabletStyle ? styles.buttonTablet : btnMobileStyle ? styles.buttonMobile : {} : {} } onClick={updateStructure} className="main__btn" > Structure </button> <button style={ surfaceActive ? btnTabletStyle ? styles.buttonTablet : btnMobileStyle ? styles.buttonMobile : {} : {} } onClick={updateSurface} className="main__btn" > Surface </button> </div> </main> )
关键说明:
- 优先级顺序:先判断平板视口(
min-width:768px),再判断移动视口(min-width:375px),避免大视口条件被小视口覆盖。 - 嵌套三元模拟else if:逻辑等价于:
if (active状态) { if (btnTabletStyle) { return styles.buttonTablet } else if (btnMobileStyle) { return styles.buttonMobile } else { return {} } } else { return {} } - 简化样式对象:移除了原样式中无用的函数参数,直接使用外部的
themeColor定义静态样式对象,更简洁高效。
如果想进一步优化代码,可以把样式判断逻辑抽成复用函数,减少重复代码:
const getActiveButtonStyle = (isActive) => { if (!isActive) return {} if (btnTabletStyle) return styles.buttonTablet if (btnMobileStyle) return styles.buttonMobile return {} } // 按钮处直接调用 style={getActiveButtonStyle(overviewActive)}
这样代码更易维护,也符合DRY原则。
内容的提问来源于stack exchange,提问作者Kade
相关产品推荐
相关产品推荐

