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
相关产品推荐
相关产品推荐

