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

React中@mdxeditor/editor无法正确渲染换行问题

解决方案

问题原因

Markdown标准里,单个换行符\n不会直接渲染成换行(需在换行前加两个空格才会生效),只有空行(两个连续\n)才会作为段落分隔。你用的MDXEditor默认遵循这个标准,同时缺少硬换行支持插件,导致数据库里的换行无法正确展示;另外*and again*没被解析成斜体,也是解析器配置的问题。

解决步骤

1. 安装硬换行解析插件

安装remark-breaks,让MDXEditor能把单个\n转换成HTML的<br>标签:

npm install remark-breaks

2. 修改MDXEditor配置

在InitializedMDXEditor组件中,添加markdownParser配置引入该插件:

import remarkBreaks from 'remark-breaks';

export default function InitializedMDXEditor({
  editorRef,
  ...props
}: { editorRef: ForwardedRef<MDXEditorMethods> | null } & MDXEditorProps) {
  return (
    <MDXEditor
      {...props}
      ref={editorRef}
      // 新增解析器配置
      markdownParser={{
        remarkPlugins: [remarkBreaks]
      }}
      plugins={[
        headingsPlugin(),
        listsPlugin(),
        quotePlugin(),
        imagePlugin(),
        tablePlugin(),
        thematicBreakPlugin(),
        markdownShortcutPlugin(),
        toolbarPlugin({
          toolbarContents: () => (
            <>
              <UndoRedo />
              <BoldItalicUnderlineToggles />
              <CodeToggle />
              <ListsToggle />
              <InsertTable />
              <InsertThematicBreak />
            </>
          ),
        }),
      ]}
    />
  );
}

3. 外部展示场景补充(若需)

如果是在MDXEditor之外展示Markdown内容,用react-markdown组件并开启breaks选项:

import ReactMarkdown from 'react-markdown';

// 展示组件中使用
<ReactMarkdown breaks>{user.notes}</ReactMarkdown>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:08:10