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

如何在react-mentions中为选中的提及内容设置不同颜色?

解决react-mentions中提及内容颜色重叠的问题

问题描述

在React项目中使用react-mentions库的MentionsInput和Mention组件时,尝试修改建议列表选中项的文本颜色,设置.mentions__mention {color: #ff0000}后,输入框中选中的用户名出现两种不同颜色的重叠效果。

问题原因

react-mentions采用双层结构实现:mentions__highlighter层负责渲染高亮样式,mentions__input层是实际输入区域,两者叠加显示。仅单独设置mentions__mention的颜色,会导致两层文本颜色或位置错位,出现视觉重叠。

修复方案

需要统一高亮层和输入层的提及文本样式,调整后的代码如下:

样式代码

.mentions--multiLine .mentions__control {
  font-family: monospace;
  font-size: 14pt;
  border: 1px solid silver;
  position: relative;
}

.mentions--multiLine .mentions__highlighter {
  padding: 9px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: transparent;
}

.mentions--multiLine .mentions__input {
  padding: 7px;
  min-height: 63px;
  outline: 0;
  border: 0;
  background: transparent;
}

/* 统一两层的提及文本颜色 */
.mentions__mention,
.mentions--multiLine .mentions__highlighter .mentions__mention {
  color: #ff0000;
}

组件代码

<MentionsInput
  value={this.state.value}
  onChange={this.handleChange}
  markup="@{{__type__||__id__||__display__}}"
  placeholder="Type anything, use the @ symbol to tag other users."
  className="mentions mentions--multiLine"
>
  <Mention type="user" trigger="@" data={userMentionData} />
</MentionsInput>

关键说明

  1. 将mentions__highlighter设为绝对定位,确保与输入层完全对齐,避免位置偏移。
  2. 让输入层背景透明、高亮层普通文本透明,仅保留提及内容的颜色,消除两层文本重叠的视觉冲突。
  3. 同时为两层的mentions__mention设置颜色,保证样式统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:48:11