fix: 代码块 [object Object] — rehype-highlight 替换 span 后 String() 失败
根因: rehype-highlight 将代码文本替换为 <span class='hljs-*'> 元素后, children 变成 React 元素数组, String(children) → '[object Object]' 修复: extractTextContent 递归提取纯文本,绕过语法高亮 span
This commit is contained in:
@@ -118,7 +118,8 @@ export function AssistantMessage({ message, isStreaming, streamContent }: Assist
|
||||
components={{
|
||||
code({ className, children, ...props }) {
|
||||
const match = /language-(\w+)/.exec(className ?? '');
|
||||
const codeStr = String(children).replace(/\n$/, '');
|
||||
// rehype-highlight 会把代码替换为 <span> 高亮元素,需提取纯文本
|
||||
const codeStr = extractTextContent(children).replace(/\n$/, '');
|
||||
if (!match) return <code className={className} {...props}>{children}</code>;
|
||||
return <CodeBlock language={match[1]} code={codeStr} />;
|
||||
},
|
||||
@@ -185,3 +186,15 @@ function CodeBlock({ language, code }: { language: string; code: string }): Reac
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/** 从 React children(可能含高亮 span)递归提取纯文本 */
|
||||
function extractTextContent(children: React.ReactNode): string {
|
||||
if (typeof children === 'string') return children;
|
||||
if (typeof children === 'number') return String(children);
|
||||
if (!children) return '';
|
||||
if (Array.isArray(children)) return children.map(extractTextContent).join('');
|
||||
if (typeof children === 'object' && 'props' in children) {
|
||||
return extractTextContent((children as React.ReactElement).props.children);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user