For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/react.md.
  • 中文
  • React 组件

    根入口与 /view 都导出视图组件;只有根入口额外导出源码组件 Wikitext。

    Warning

    这些组件在模块加载时创建 Context,并使用 useId / useMemo,只能在客户端组件中运行。根入口与 /view 的产物顶部带有 "use client" 指令,在 Next.js App Router 等环境中可以直接使用;服务端只调用 /parse 与 /hast。

    Wikitext

    import { Wikitext } from "react-wikitext";
    import "react-wikitext/styles.css";
    
    <Wikitext source={source} lang="zh-CN" />;

    源码组件在内部完成解析、准备与渲染,只支持同步管线。

    属性

    interface WikitextProps extends Omit<WikitextViewProps, "document"> {
      source: string;
      parser?: WikitextParser;
      parseOptions?: WikitextParseOptions;
      prepareOptions?: WikitextPrepareOptions;
      onError?: (error: Error, info: { stage: "parse" | "prepare" }) => void;
      fallback?:
        React.ReactNode | ((error: Error, info: { stage: "parse" | "prepare" }) => React.ReactNode);
    }
    属性说明
    source待渲染的 wikitext 源码
    parser复用已创建的解析器;缺省使用默认配置的共享解析器
    parseOptions解析选项,见 /parse
    prepareOptions准备选项,见 /hast
    onError解析/准备失败回调,info.stage 区分阶段
    fallback失败时渲染的内容
    components按 HTML 标签覆盖组件
    semanticComponents按 wiki 语义类型覆盖组件
    lang / dir写入根容器的语言与方向
    idPrefix实例标题 id 前缀;只在 headingIdStrategy: "instance" 下生效,非法/空值回退到 useId
    className与 wtr-view 合并
    containerProps根容器的额外属性;类型层排除 dangerouslySetInnerHTML
    onRenderError单个块渲染失败时的回调

    行为

    • 解析与准备分别用 useMemo 缓存,依赖为 [parser, source, parseOptions] 与 [document, prepareOptions]。
    • 每次渲染传入新的选项对象会导致重新解析;请固定引用。
    • 插件与解析函数必须是纯函数;异步插件会抛 ASYNC_PLUGIN_IN_SYNC_PATH。
    • 默认解析器在模块加载时初始化;不需要解析器时使用 /view。

    WikitextView

    import { WikitextView } from "react-wikitext/view";
    
    <WikitextView document={prepared} lang="zh-CN" />;

    WikitextView 只接收准备完成的渲染快照。渲染期间不解析源码、不运行插件或解析函数。

    属性

    属性说明
    documentWikitextRenderDocument
    components按 HAST 标签名覆盖组件
    semanticComponents按 wiki 语义类型覆盖组件
    lang / dir写入根容器的语言与方向
    idPrefixinstance 策略下的实例前缀;未传时使用 useId
    className与 wtr-view 合并
    containerProps根容器属性;排除 dangerouslySetInnerHTML
    onRenderError块级渲染失败回调
    • 根节点固定为 div.wtr-view。
    • idPrefix 同时影响标题 id、文档内 #fragment 链接与表格 headers。
    • 每个顶层块包在错误边界内;一个块失败不会影响其他块。
    • 视图内部建立语义索引与 HAST 索引,供组件与 WikitextFragment 使用。

    WikitextFragment

    import { WikitextFragment } from "react-wikitext/view";
    
    <WikitextFragment nodes={node.children} mode="block" />;
    属性说明
    nodes当前渲染文档中的语义节点数组
    mode"inline"(默认)或 "block"
    className可选外层类名
    • 必须在 <WikitextView> 的 Context 内使用,否则抛错。
    • nodes 必须是当前视图渲染文档中的同一批节点对象;仅 id 相同并不够。
    • 只渲染能在准备结果 HAST 索引中找到的节点,适合模板参数、文件说明与 ref 内容。
    • inline 模式无 className 时不额外包裹 DOM;有 className 时使用 <span>;block 模式使用 wtr-fragment 容器。
    • 同一视图内重复渲染同一节点会产生重复内容与重复标题 id。

    组件覆盖

    HTML 组件

    type WikitextHtmlComponents = Partial<
      Record<string, React.ComponentType<WikitextHtmlComponentProps>>
    >;
    
    interface WikitextHtmlComponentProps extends React.HTMLAttributes<HTMLElement> {
      node?: import("hast").Element;
      document: WikitextRenderDocument;
      semantic?: WikitextNode;
      origin?: WikitextOrigin;
      children?: React.ReactNode;
      href?: string;
      src?: string;
      alt?: string;
    }

    按键名映射,例如 p、table、img、a。组件收到经过安全校验的 DOM 属性,以及 HAST 元素、文档和可选的语义节点。

    语义组件

    type WikitextSemanticComponents = {
      link?: React.ComponentType<WikitextLinkComponentProps>;
      template?: React.ComponentType<WikitextTemplateComponentProps>;
      parserFunction?: React.ComponentType<WikitextTemplateComponentProps>;
      argument?: React.ComponentType<WikitextSemanticComponentProps<WikitextArgument>>;
      file?: React.ComponentType<WikitextFileComponentProps>;
      reference?: React.ComponentType<WikitextReferenceComponentProps>;
      extension?: React.ComponentType<WikitextExtensionComponentProps>;
      unknown?: React.ComponentType<WikitextUnknownComponentProps>;
      table?: React.ComponentType<WikitextSemanticComponentProps<WikitextTable>>;
    };

    所有语义组件都会收到:

    interface WikitextSemanticComponentProps<Node extends WikitextNode> {
      document: WikitextRenderDocument;
      node: Node;
      hastNode: import("hast").Element;
      origin?: WikitextOrigin;
      children?: React.ReactNode;
    }

    额外字段:

    类型额外属性
    linktarget、kind、href?、external
    template / parserFunctiondisplayName
    filename
    referencenumber
    extensionname、block
    unknownparsedType、block

    优先级:显式语义组件替换整个语义结构;未替换时,默认 HAST 内部的标签继续应用 components;最后回退到原生元素。

    自定义模板卡片

    import { WikitextFragment, type WikitextTemplateComponentProps } from "react-wikitext/view";
    
    function TemplateCard({ displayName, node }: WikitextTemplateComponentProps) {
      return (
        <aside className="template-card">
          <strong>{displayName}</strong>
          <WikitextFragment nodes={node.children} mode="block" />
        </aside>
      );
    }
    
    <WikitextView document={prepared} semanticComponents={{ template: TemplateCard }} />;

    自定义链接

    <WikitextView
      document={prepared}
      semanticComponents={{
        link: ({ href, external, children }) =>
          href ? (
            <a
              href={href}
              {...(external ? { target: "_blank", rel: "nofollow noopener noreferrer" } : {})}
            >
              {children}
            </a>
          ) : (
            <span className="unresolved-link">{children}</span>
          ),
      }}
    />

    Context Hook

    interface WikitextViewContextValue {
      document: WikitextRenderDocument;
      semanticIndex: ReadonlyMap<string, WikitextNode>;
      hastIndex: ReadonlyMap<string, import("hast").ElementContent>;
      components: WikitextHtmlComponents;
      semanticComponents: WikitextSemanticComponents;
      idPrefix: string;
      mapId: (id: string) => string;
      mapHref: (href: string) => string;
      onRenderError?: (error: Error, info: { node: WikitextNode }) => void;
    }
    
    function useWikitextContext(): WikitextViewContextValue;
    function useWikitextLabels(): WikitextLabels;
    function useWikitextIds(): { toDomId(id: string): string; toHref(href: string): string };
    • 这些 Hook 必须在 <WikitextView> 内使用。
    • useWikitextLabels() 读取渲染快照中的最终文案。
    • useWikitextIds() 适合需要在自定义组件中生成锚点或片段链接的场景。

    渲染错误

    <Wikitext
      source={source}
      onRenderError={(error, { node }) => {
        reportError(error, { nodeType: node.type, nodeId: node.id });
      }}
    />

    错误边界按顶层 HAST 块隔离。占位内容显示 labels.renderFailed、节点类型与源码。解析与准备错误不会进入错误边界,应由调用方捕获。

    相关类型

    根入口额外导出视图组件会用到的精选语义类型:WikitextLink、WikitextTemplate、WikitextFile、WikitextReference、WikitextTable、WikitextUnknown 等。完整节点子类型与 AST 工具从 /ast 导入。