将 MDX 与 NextJS 13 结合使用返回 useContext 错误

Fel*_*vêa 2 typescript reactjs next.js mdxjs

我正在尝试在 Next.js 13 中使用 mdx 文件。我已经在 next.config 中完成了所有必要的配置并创建了该文件。在应用程序文件夹内,我有 > docs > Components > Accordion > page.mdx

页面文件只渲染一个类似“#Title”的标题。当我导航到此 URL 时,出现以下错误:

node_modules/@mdx-js/react/lib/index.js (34:26) @ React 错误 - createContext 仅适用于客户端组件。在文件顶部添加“use client”指令以使用它。了解更多: https: //nextjs.org/docs/messages/context-in-server-component

我该如何解决这个问题?

我的 next.config.js

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
  },
})

/** @type {import('next').NextConfig} */
const nextConfig = {
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  experimental: {
    appDir: true,
  },
}

module.exports = withMDX(nextConfig)
Run Code Online (Sandbox Code Playgroud)

Mat*_*yot 7

在项目的根目录中,确保添加文件 mdx-components.tsx:

import type { MDXComponents } from "mdx/types";

// This file is required to use MDX in `app` directory.
export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    // Allows customizing built-in components, e.g. to add styling.
    // h1: ({ children }) => <h1 style={{ fontSize: "100px" }}>{children}</h1>,
    ...components,
  };
}
Run Code Online (Sandbox Code Playgroud)

另外,我的 next.config.js 看起来像这样(与下面提供的示例相同),但我已经尝试过你的,它也工作正常:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: true,
  },
};

const withMDX = require("@next/mdx")();
module.exports = withMDX(nextConfig);

Run Code Online (Sandbox Code Playgroud)

另外,您可以看一下这个示例:https://github.com/vercel/next.js/tree/canary/examples/app-dir-mdx