draftjs - 编辑实体的装饰文本

标签 draftjs

我们有一个 Figure 装饰器,它允许我们插入一个链接,您可以将鼠标悬停在该链接上以预览图像。我们使用模态形式插入此图像以及一些元数据(标题等)。这一切都很好。但是,我们还希望能够单击链接并弹出模式进行编辑。

Entity.replaceData() 对于更新元数据非常有效,唯一剩下的问题是来自模式的装饰文本。看来该实体对其所装饰的内容知之甚少甚至一无所知。

我们如何查找和替换文本?有办法解决这个问题吗?

(我尝试将草稿中的内容设置为任意单个字符并使装饰器显示内容/标题(这很好),但是当尝试删除该图形时,草稿似乎会跳过内容并删除它之前的一些内容。我猜这是由于文本长度不同。我认为将其设置为“IMMUTABLE”可以解决这个问题,但这没有帮助。)

编辑:

这是我的装饰器:

function LinkedImageDecorator(props: Props) {
  Entity.mergeData(props.entityKey, { caption: "hello world" });

  const entity = Entity.get(props.entityKey);
  const data = entity.getData();
  return <LinkedImage data={data} text={props.children} offsetKey={props.offsetKey} />
}

function findLinkedImageEntities(contentBlock: ContentBlock, callback: EntityRangeCallback) {
  contentBlock.findEntityRanges((character) => {
    const entityKey = character.getEntity();
    return (
      entityKey != null &&
      Entity.get(entityKey).getType() === ENTITY_TYPE.IMAGE
    );
  }, callback);
}

export default {
  strategy: findLinkedImageEntities,
  component: LinkedImageDecorator,
  editable: false,
};

如您所见,我正在测试 Entity.mergeData ,它最终将是我的 LinkedImage 组件的回调(这将打开模态 onClick。)所以元数据很容易更新,我只需要能够更新作为 props.children 传入的装饰文本。

最佳答案

所以我终于在Jiang YD的帮助下解决了这个问题。和 tobiasandersen 。这里...

首先,我注入(inject)装饰器并引用我的编辑器(它跟踪 EditorState):

const decorators = new CompositeDecorator([{
  strategy: findLinkedImageEntities,
  component: LinkedImageDecorator,
  props: { editor: this }
}];

this.editorState = EditorState.set(this.editorState, { decorator });

从那里我可以在我的 LinkedImageDecorator 中执行此操作:

const { decoratedText, children, offsetKey, entityKey, editor } = this.props;

// This looks messy but seems to work fine
const { startOffset, blockKey } = children['0'].props;

const selectionState = SelectionState.createEmpty(blockKey).merge({
  anchorOffset: startOffset,
  focusOffset: startOffset + decoratedText.length,
});

const editorState = editor.getEditorState();

let newState = Modifier.replaceText(
  editorState.getCurrentContent(),
  selectionState,
  "my new text",
  null,
  entityKey,
);

editor.editorState = EditorState.push(editorState, newState, 'insert-fragment');

不确定这是否是最干净的方法,但似乎效果很好!

关于draftjs - 编辑实体的装饰文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918557/

相关文章:

javascript - React Draft.js 所见即所得 : How to programmatically insert text at the cursor location?

javascript - 由于装饰器过多,随着内容的增加,Draft js Editor 变慢了

javascript - 使用 Draft.js 从字符串创建状态时设置光标位置

reactjs - 如何在draft.js 中实现链接?

javascript - 如何在 draft.js 中设置默认字体系列和大小

javascript - 如何在 Draft.js 中创建基于开始和结束的选择?

javascript - 如何用javascript替换HTML字符串中的字符

javascript - 如何使用draft.js插入图像?