【问题标题】:How to ignore empty lines while wrapping nodes with SlateJS?如何在使用 SlateJS 包装节点时忽略空行?
【发布时间】:2022-11-28 20:52:07
【问题描述】:

我正在使用 Slate.js 构建富文本编辑器。我设置了一个内联格式,我可以使用以下函数进行切换:

toggleInline: function (editor, format) {
  const isActive = this.isFormatActive(editor, format, TYPES.FORMATS.INLINE);

  if (isActive) {
    Transforms.unwrapNodes(editor, {
      match: node => !this.isEditor(node) && Element.isElement(node) && node.type === format
    });

  } else {
    const inline = { type: format, children: noChildren };
    Transforms.wrapNodes(editor, inline, { split: true });
  }
}

它工作正常,但如果我选择多行,我想忽略空行,这样就不会插入空块。例如,这里我只想包装 AB 而不是空行:

相应的孩子看起来像这样:

[
  { type: "p", children: [{ text: "A" }]},
  { type: "p", children: [{ text: "" }]},
  { type: "p", children: [{ text: "B" }]}
]

我试图在 wrapNodes 上添加一个 match 选项,但它会擦除空行而不是跳过它们:

Transforms.wrapNodes(editor, inline, {
  match: node => node.text !== emptyString
  split: true
});

我能怎么做?

【问题讨论】:

    标签: javascript reactjs slatejs


    【解决方案1】:

    事实证明 match 选项是可行的方法,我只需要使用适当的函数来检查元素是否为空:

    Transforms.wrapNodes(editor, inline, {
      match: (node) => !Element.isEmpty(node),
      split: true
    });
    

    我的自定义 isEmpty 函数:

    isEmpty: function (element) {
      if ("text" in element) return element.text === emptyString;
      if (element.children.length > 1) return false;
    
      return this.isEmpty(head(element.children));
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2019-01-16
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2022-12-28
      相关资源
      最近更新 更多