You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:41:05