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

如何在Draft.js中高亮以美元符号($)开头的词汇?

在Draft.js中为$开头的词汇设置字体颜色

要实现这个功能,核心是利用Draft.js的自定义装饰器(Decorator)——这也是StockTwits、Twitter实现股票代码/话题标签高亮的核心逻辑,能自动识别特定格式文本并应用自定义样式。

实现步骤:

  1. 定义文本匹配策略
    编写策略函数,通过正则匹配所有以$开头的词汇:

    const dollarSymbolStrategy = (contentBlock, callback, contentState) => {
      const text = contentBlock.getText();
      // 匹配$后接字母数字的词汇,可按需调整正则规则
      const regex = /\$[A-Za-z0-9]+/g;
      let match;
      while ((match = regex.exec(text)) !== null) {
        // 告知装饰器匹配文本的起止位置
        callback(match.index, match.index + match[0].length);
      }
    };
    
  2. 创建自定义装饰组件
    定义渲染高亮文本的组件,设置目标字体颜色:

    const DollarSymbolSpan = (props) => {
      return (
        <span style={{ color: '#2563EB', fontWeight: '500' }}>
          {props.children}
        </span>
      );
    };
    
  3. 绑定装饰器到编辑器
    组合策略与组件生成装饰器,初始化编辑器状态时传入:

    import React from 'react';
    import { Editor, EditorState, Decorator } from 'draft-js';
    
    class DollarHighlightEditor extends React.Component {
      constructor(props) {
        super(props);
        // 创建装饰器实例
        const decorator = new Decorator({
          strategies: [dollarSymbolStrategy],
          component: DollarSymbolSpan,
        });
        // 用装饰器初始化编辑器状态
        this.state = {
          editorState: EditorState.createEmpty(decorator),
        };
      }
    
      onChange = (editorState) => {
        this.setState({ editorState });
      };
    
      render() {
        return (
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
          />
        );
      }
    }
    
    export default DollarHighlightEditor;
    

补充说明:

  • 正则规则可按需调整,比如支持包含特殊字符的词汇
  • 样式完全自定义,除颜色外还可添加背景色、下划线等效果
  • 若需和其他装饰器(如@提及、话题标签)共存,只需将对应策略函数加入strategies数组即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:20:36