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

如何将Lexical富文本编辑器默认节点从段落改为项目符号列表?

将Lexical默认节点改为项目符号列表

要实现编辑器首次渲染后默认显示项目符号列表,且回车时创建新的列表项而非段落,你需要修改编辑器的初始状态配置,结合已有插件的逻辑来实现,具体操作如下:

1. 导入必要的节点创建工具

在文件顶部添加Lexical内置的节点创建函数:

import { $createEditorState, $createListNode, $createListItemNode, $createParagraphNode } from 'lexical';

2. 修改编辑器配置的初始状态

在editorConfig中添加initialEditorState属性,初始化编辑器为包含空列表项的无序列表:

const editorConfig = {
  namespace: "MyEditor",
  theme: ExampleTheme,
  onError(error: any) {
    throw error;
  },
  nodes: [
    HeadingNode,
    ListNode,
    ListItemNode,
    QuoteNode,
    CodeNode,
    CodeHighlightNode,
    TableNode,
    TableCellNode,
    TableRowNode,
    AutoLinkNode,
    LinkNode,
  ],
  // 配置初始编辑器状态
  initialEditorState: () => {
    // 创建无序列表节点(传入'number'可改为有序列表)
    const listNode = $createListNode('bullet');
    // 创建列表项节点
    const listItemNode = $createListItemNode();
    // 给列表项添加空段落,确保编辑器有可输入区域
    listItemNode.append($createParagraphNode());
    // 将列表项加入列表
    listNode.append(listItemNode);
    // 返回包含该列表的初始编辑器状态
    return $createEditorState(listNode);
  },
};

3. 验证回车行为

由于你已经引入了ListPlugin,当在列表项末尾按下回车键时,Lexical会自动创建新的列表项,而非段落。常规的列表编辑逻辑已被插件覆盖,无需额外自定义按键处理。

修改后的完整编辑器代码:

import { $createEditorState, $createListNode, $createListItemNode, $createParagraphNode } from 'lexical';
// 保留你原有的其他导入

const editorConfig = {
  namespace: "MyEditor",
  theme: ExampleTheme,
  onError(error: any) {
    throw error;
  },
  nodes: [
    HeadingNode,
    ListNode,
    ListItemNode,
    QuoteNode,
    CodeNode,
    CodeHighlightNode,
    TableNode,
    TableCellNode,
    TableRowNode,
    AutoLinkNode,
    LinkNode,
  ],
  initialEditorState: () => {
    const listNode = $createListNode('bullet');
    const listItemNode = $createListItemNode();
    listItemNode.append($createParagraphNode());
    listNode.append(listItemNode);
    return $createEditorState(listNode);
  },
};

const Editor = () => {
  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <ToolbarPlugin />
        <div className="editor-inner">
          <RichTextPlugin
            contentEditable={<ContentEditable className="editor-input" />}
            placeholder={<Placeholder />}
            ErrorBoundary={LexicalErrorBoundary}
          />
          <HistoryPlugin />
          <AutoFocusPlugin />
          <ListPlugin />
          <LinkPlugin />
        </div>
      </div>
    </LexicalComposer>
  );
};

export default Editor;

完成上述修改后,编辑器首次渲染会显示空的项目符号列表项,按下回车键将自动生成新的列表项,替代默认的段落创建行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:53:12