我尝试在 NextJs 13 中使用 typescript 来使用“react-markdown”。 问题是打字稿不断抱怨“代码”方法的道具, 我在谷歌上搜索找到了导入“CodeProps”的解决方案。 尝试使用一些自定义类型或简单地给出“任何”,但都不起作用。
CodeProps 是否因某些更新而不再存在? 或者这是因为 NextJs 的更新而发生的?
'use client';
import ReactMarkdown, { CodeProps } from 'react-markdown';
// error msg: can't find the module 'react-markdown/lib/ast-to-react'
import { CodeProps } from 'react-markdown/lib/ast-to-react';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
const Markdown = ({ content }: { content: string }) => {
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({ node, inline, className, children, ...props }: CodeProps) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
style={oneDark}
PreTag='div'
language={match[1]}
{...props}>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code className={className ? className : ''} {...props}>
{children}
</code>
);
},
}}>
{content}
</ReactMarkdown>
);
};
export default Markdown;
缓解此问题的最简单方法可能是创建自己的界面。
interface CodeProps {
node?: any,
inline?: any,
className?: any,
children?: any,
}
Components["code"]
,但事实证明这还不够。
我一直在做的是使用底层
JSX.IntrinsicElements
类型加上 ExtraProps
中的 react-markdown
来获取正确的类型:
import ReactMarkdown, { ExtraProps } from "react-markdown";
<ReactMarkdown
components={{
code: (props: JSX.IntrinsicElements["code"] & ExtraProps) => {
const {children, className, node, ...rest} = props
const match = /language-(\w+)/.exec(className || '')
return match ? (
<SyntaxHighlighter
{...rest}
PreTag="div"
children={String(children).replace(/\n$/, '')}
language={match[1]}
style={dark}
/>
) : (
<code {...rest} className={className}>
{children}
</code>
)
},
}}
>