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

如何基于比较运算符控制元素展示,仅显示符合条件的最高阈值标识

问题原因

你的代码存在两处核心问题:

  • 三个判断为独立if分支,没有互斥逻辑,只要满足条件就会重复插入多个标识
  • 你描述的「发帖数200时三个标识全部显示」的问题,是实际代码中误将比较符写为>=导致的,200同时满足>=10/>=50/>=100三个条件,所以三个标识都会被插入。同时你原本的<=逻辑无法覆盖100以上的发帖数场景,和你要求的「超过100仍展示<=100标识」的需求不符。
修复方案

从最高阈值往最低阈值做互斥判断即可:

if (userPosts <= 10) {
  vnode.children.push(
    <span className="auto-badge"><i class="fas fa-baby autopost"/> less than 10 posts</span>
  );
} else if (userPosts <= 50) {
  vnode.children.push(
    <span className="auto-badge"><i class="fas fa-child autopost"/> less than 50 posts</span>
  );
// 所有>50的情况,包括超过100的场景,都展示<=100的标识
} else {
  vnode.children.push(
    <span className="auto-badge"><i class="fas fa-bullhorn autopost"/> less than 100 posts</span>
  );
}
更易维护的优化写法

如果后续有新增档位的需求,可以把配置统一抽离,自动匹配最高符合条件的档位:

// 按阈值从小到大排列,最后一位用Infinity覆盖所有超阈值场景
const badgeConfigs = [
  { threshold: 10, icon: 'fa-baby', text: 'less than 10 posts' },
  { threshold: 50, icon: 'fa-child', text: 'less than 50 posts' },
  { threshold: Infinity, icon: 'fa-bullhorn', text: 'less than 100 posts' }
]
// 找到第一个符合条件的档位
const matchedBadge = badgeConfigs.find(item => userPosts <= item.threshold)
vnode.children.push(
  <span className="auto-badge"><i class={`fas ${matchedBadge.icon} autopost`}/> {matchedBadge.text}</span>
)

内容的提问来源于stack exchange,提问作者juniorDevFla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:04