React:多路径匹配Footer主题,三元运算符或switch如何实现?
问题原因与解决方案
你的代码问题出在var urlString = '/work' || '/wip' || '/journal';这行——||逻辑或运算符会返回第一个“真值”,所以urlString永远等于/work,自然只有这个路径能触发深色主题。
下面是几种可行的解决方式:
方式一:直接在判断中使用逻辑或
把路径判断直接写在三元表达式里,用||连接多个匹配条件:
<FooterContainer theme={ window.location.pathname === '/work' || window.location.pathname === '/wip' || window.location.pathname === '/journal' ? 'dark' : 'light' }>
方式二:用数组+includes方法(推荐)
把需要深色主题的路径存在数组里,用includes方法判断当前路径是否在数组中,代码更简洁易维护:
const darkThemePaths = ['/work', '/wip', '/journal']; <FooterContainer theme={ darkThemePaths.includes(window.location.pathname) ? 'dark' : 'light' }>
方式三:switch语句
如果后续有更复杂的判断逻辑,可以用switch,但对于当前简单的多值匹配,这种方式稍显繁琐:
let theme = 'light'; switch(window.location.pathname) { case '/work': case '/wip': case '/journal': theme = 'dark'; break; } <FooterContainer theme={theme}>
内容的提问来源于stack exchange,提问作者Sam St Aubyn
相关产品推荐
相关产品推荐

