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

Draft.js中如何检测指定自定义样式是否在编辑器全文中被使用?

Draft.js 全文档指定内联样式检测方案

你可以通过遍历内容块的样式范围实现需求,具体实现逻辑如下:

  • 从editorState实例中获取全文档的ContentState对象
  • 遍历ContentState下的所有ContentBlock内容块
  • 对每个内容块调用findStyleRanges方法匹配目标样式,只要存在任意匹配项即可判定该样式被使用

可直接使用的代码实现

function checkStyleExists(editorState, targetStyleName) {
  const content = editorState.getCurrentContent();
  // 遍历所有内容块
  for (const block of content.getBlocksAsArray()) {
    let isStyleExist = false;
    block.findStyleRanges(
      // 匹配携带目标样式的字符
      charMeta => charMeta.hasStyle(targetStyleName),
      // 匹配到后标记存在并终止当前块的遍历
      () => {
        isStyleExist = true;
        return true;
      }
    );
    if (isStyleExist) return true;
  }
  return false;
}

// 调用示例
const hasStrikethrough = checkStyleExists(editorState, 'STRIKETHROUGH');

说明

该方案不需要逐字符遍历全文档,匹配到目标样式后会提前终止遍历,性能开销极低,适配所有版本的Draft.js。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:07