You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用React时,Lexical Decorator Node的decorate方法返回什么?

Lexical Decorator Node(无React):decorate方法返回值说明

当不使用React时,Lexical Decorator Node的decorate方法需要返回一个原生DOM元素——即通过浏览器原生API(如document.createElement)创建的DOM节点,该节点会直接被Lexical渲染到编辑器中。

结合你要实现“显示图片+静态文本的不可编辑节点”的需求,以下是完整的节点实现示例:

import { DecoratorNode } from 'lexical';

class StaticImageTextNode extends DecoratorNode {
  static getType() {
    return 'static-image-text';
  }

  static clone(node) {
    return new StaticImageTextNode(node.__imageUrl, node.__text);
  }

  constructor(imageUrl, text) {
    super();
    this.__imageUrl = imageUrl;
    this.__text = text;
  }

  decorate() {
    // 创建容器节点,设置不可编辑
    const container = document.createElement('div');
    container.contentEditable = 'false';
    container.style.display = 'flex';
    container.style.alignItems = 'center';
    container.style.gap = '12px';
    container.style.padding = '8px';
    container.style.border = '1px solid #eee';
    container.style.borderRadius = '4px';

    // 创建图片元素
    const img = document.createElement('img');
    img.src = this.__imageUrl;
    img.alt = 'static content image';
    img.style.width = '48px';
    img.style.height = '48px';
    img.style.objectFit = 'cover';
    img.style.borderRadius = '4px';

    // 创建文本元素
    const textSpan = document.createElement('span');
    textSpan.textContent = this.__text;
    textSpan.style.fontSize = '14px';

    // 组装DOM结构
    container.appendChild(img);
    container.appendChild(textSpan);

    return container;
  }

  exportJSON() {
    return {
      type: 'static-image-text',
      imageUrl: this.__imageUrl,
      text: this.__text,
      version: 1,
    };
  }

  static importJSON(serializedNode) {
    return new StaticImageTextNode(serializedNode.imageUrl, serializedNode.text);
  }
}

关键说明:

  • 必须返回合法的原生DOM节点,任何通过document.createElement创建的元素(如div、img、span等)都可以,你可以自由组合结构、设置样式。
  • 设置contentEditable="false"可以确保该节点在编辑器中不可编辑,完全符合你的需求。
  • 需实现clone、exportJSON、importJSON方法,保证节点能正常被Lexical处理(复制、序列化/反序列化)。

内容的提问来源于stack exchange,提问作者Jonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:03:27