【问题标题】:How do I make multiline hilighter on draft-js?如何在 Draft-js 上制作多行加亮器?
【发布时间】:2016-08-11 10:30:20
【问题描述】:

现在我制作 Markdown 荧光笔。

突出显示内联并不难。我使用 CompositeDecorator 来重写文本。 https://facebook.github.io/draft-js/docs/advanced-topics-decorators.html

但我不能使用多行语法(例如,代码块)。默认情况下,换行符成为下一个块,装饰器由块到块处理。

下图是我的实现示例。我无法修饰代码块语法。

如何在 Draft-js 上制作多行荧光笔?

【问题讨论】:

    标签: draftjs


    【解决方案1】:

    取决于您想要的“突出显示”样式。如果您只想要一些颜色或字体大小,大多数情况下内联样式就足够了。检查color 示例。

    对于块样式,您需要自定义 CSS 类并将块映射到您的类,请参阅 this

    【讨论】:

    • 我可以在内容块中实现高亮文本(例如那个颜色示例),但是从原始文本中检测代码块语法并对其进行装饰仍然很困难。
    • 我不知道您需要从原始文本中检测代码块。如果您通过检测原始文本来应用代码语法,那么新块(没有任何原始文本)如何告诉您它是“代码块”?
    【解决方案2】:

    我找到了解决办法。在 blockRendererFn 上通过 dand 检测 markdown 代码块。

    // use blockRedererFn
    <Editor
      blockRendererFn={(block) => blockRenderer(block, this.state.editorState)}
      editorState={this.state.editorState}
    />;
    
    // detect code block and add fontFamily: monospace
    // Example
    //
    // ```
    // here
    // ```
    function blockRenderer(contentBlock, editorState) {
      const type = contentBlock.getType();
      if (type === "unstyled") {
        const allText = editorState.getCurrentContent().getPlainText();
        const allCount = countCodeBlockHeader(allText);
        if (allCount > 0 && allCount % 2 === 0) {
          const contentText = contentBlock.getText();
          const [before, after] = allText.split(contentText);
          const beforeCount = countCodeBlockHeader(before);
          const afterCount = countCodeBlockHeader(after);
          if (beforeCount % 2 === 1) {
            if (afterCount % 2 === 1) {
              return {
                component: (_props) => {
                  return <code style={{
                    fontFamily: "monospace",
                    direction: "ltr",
                    unicodeBidi: "bidi-override",
                  }}>{contentText}</code>;
                },
                editable: true
              };
            }
          }
        }
      }
    }
    
    function countCodeBlockHeader(text) {
      return text
      .split("\n")
      .filter(l => l.match(new RegExp("^(```)")))
      .length;
    }
    

    但它很脏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2021-11-10
      • 2017-02-10
      • 1970-01-01
      相关资源
      最近更新 更多