Next.js 14 App Router中rehype-mdx-code-props无法传递自定义Props
问题描述
我正在使用Next.js 14的App Router,通过MDX构建文档并需要添加代码块作为参考。尝试使用rehype-mdx-code-props将自定义Props传递给组件,代码块示例:
function sayHello(name) { console.log('Hello', name); }
在src/mdx-components.tsx中的配置如下:
export function useMDXComponents(components: MDXComponents): MDXComponents { return { h1: ({ children }) => ( <h1 className="text-3xl font-bold tracking-tight">{children}</h1> ), img: (props) => ( <Image sizes="100vw" style={{ width: "100%", height: "auto" }} {...(props as ImageProps)} /> ), code: ({children}) => { return <MyCodeBlock children={children} />; }, p: ({ children }) => ( <p className="text-sm text-muted-foreground">{children}</p> ), ...components, }; }
问题在于code: ({children})部分,打印传递的Props时发现只有children和classname被传递,导致filename和filetype参数无法传递到MyCodeBlock组件。如何让组件获取到这两个参数?
附next.config.mjs配置:
import createMDX from '@next/mdx' import remarkGfm from 'remark-gfm' import rehypeMdxCodeProps from 'rehype-mdx-code-props' /** @type {import('next').NextConfig} */ const nextConfig = { pageExtensions: ['js', 'jsx', 'md', 'mdx', 'ts', 'tsx'], } const withMDX = createMDX({ options: { remarkPlugins: [remarkGfm], rehypePlugins: [rehypeMdxCodeProps], }, }) export default withMDX(nextConfig)
解决方案
1. 修改MDX组件中<code>的接收逻辑
你当前的<code>组件仅解构了children,没有接收rehype-mdx-code-props解析出的filename、filetype等自定义属性。需要改为接收完整的props对象,并将所有属性传递给MyCodeBlock:
修改src/mdx-components.tsx中的code项:
code: (props) => { // 直接将所有props传递给自定义组件 return <MyCodeBlock {...props} />; },
或者如果你需要显式解构属性:
code: ({ children, filename, filetype, className, ...rest }) => { return <MyCodeBlock children={children} filename={filename} filetype={filetype} className={className} {...rest} />; },
2. 确保自定义组件支持对应Props
在MyCodeBlock组件中,需要定义对应的props类型,确保能接收filename和filetype:
// 示例MyCodeBlock组件 interface MyCodeBlockProps { children: React.ReactNode; filename?: string; // 对应代码块中的filename属性 filetype?: string; // 对应代码块中的filetype属性 className?: string; // MDX自动传递的语言类名,比如"language-js" } export function MyCodeBlock({ children, filename, filetype, className }: MyCodeBlockProps) { return ( <div className="code-block-container"> {/* 显示文件名 */} {filename && <div className="code-filename">{filename}</div>} {/* 显示代码内容 */} <pre className={className}> <code>{children}</code> </pre> </div> ); }
3. 验证插件配置
确认next.config.mjs中rehype-mdx-code-props已正确添加到rehypePlugins数组中,你当前的配置是正确的,无需修改。
这样修改后,filename和filetype就能正常传递到MyCodeBlock组件中了。
内容的提问来源于stack exchange,提问作者vivek gupta
相关产品推荐
相关产品推荐

