首页 > 解决方案 > 有没有办法在 Draftjs 中添加牢不可破的实体?

问题描述

我正在使用 Draftjs 编辑器。我有一个装饰器,它通过正则表达式检测一些文本并生成一个自制组件。这是调用 API 并通过将初始文本替换为 API 的结果来返回结果。

我想让这个结果成为一个不可破坏、不可编辑的实体,但我不知道该怎么做。

这是我用来替换值的函数

/**
   * Replace text in editor
   *
   * @param {Object} editorState  - State of the editor
   * @param {string} search       - Search value
   * @param {string} replaceValue - replacement value
   *
   * @returns {Object} Returns the new editorState with link removed
   */
  static replace(editorState, search, replaceValue) {

    if (typeof search === 'undefined' || search === null) {
      return editorState;
    }

    const regex = new RegExp(escapeStringRegexp(search), 'g');
    const blockMap = editorState.getCurrentContent().getBlockMap();
    const selectionsToReplace = [];
    blockMap.forEach((contentBlock) => (
      findWithRegex(regex, contentBlock, (start, end) => {
        const blockKey = contentBlock.getKey();
        const blockSelection = SelectionState
          .createEmpty(blockKey)
          .merge({
            anchorOffset: start,
            focusOffset: end,
          });

        selectionsToReplace.push(blockSelection)
      })
    ));

    let contentState = editorState.getCurrentContent();

    selectionsToReplace.forEach(selectionState => {
      contentState = Modifier.replaceText(contentState, selectionState, replaceValue)
    });

    return draftEditorState.push(editorState, contentState);
  }

我想要的是结果可以作为全局部分移动或删除并且不能更改。

谢谢你的帮助。

标签: entitydraftjs

解决方案


我认为您正在寻找的是 Draftjs' entities。假设您使用 应用实体IMMUTABLE,它将被视为不可编辑,如果您尝试删除部分单词,则整个内容将被删除。

这是一个使用实体但使用预先标记的段的官方Draftjs 示例。我认为在你的情况下,它就像在里面做这样的事情一样简单findWithRegex(还没有测试过,所以这可能是一种方法——只是想把这个想法传达出去):

let newContentState = editorState.getCurrentContent();

findWithRegex(regex, contentBlock, (start, end) => {
  const blockKey = contentBlock.getKey();
  const blockSelection = SelectionState
    .createEmpty(blockKey)
    .set("anchorOffset", start)
    .set("focusOffset", end);

  const searchEntity = content.createEntity(
    "SEARCH", // type
    "MUTABLE", // mutability <--
  );
  const entityKey = content.getLastCreatedEntityKey();

  newContentState = Modifier.applyEntity(searchEntity, blockSelection, entityKey);
})

return EditorState.push(editorState, newContentState, "apply-search-styling");

推荐阅读