From 460ed87ad2baab95aee910a52da494f1a7d64dd3 Mon Sep 17 00:00:00 2001 From: Snowykami Date: Mon, 28 Jul 2025 11:24:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96extractText?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E7=9A=84=E7=B1=BB=E5=9E=8B=E5=A3=B0=E6=98=8E?= =?UTF-8?q?=EF=BC=8C=E5=A2=9E=E5=BC=BA=E7=B1=BB=E5=9E=8B=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/components/markdown-codeblock.tsx | 34 +++++++++++++---------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/web/src/components/markdown-codeblock.tsx b/web/src/components/markdown-codeblock.tsx index 6d7084f..0642e16 100644 --- a/web/src/components/markdown-codeblock.tsx +++ b/web/src/components/markdown-codeblock.tsx @@ -2,26 +2,31 @@ import React from "react"; import { toast } from "sonner"; -function extractText(node: any): string { +// 更安全的类型声明 +function extractText(node: React.ReactNode): string { if (typeof node === "string") return node; if (Array.isArray(node)) return node.map(extractText).join(""); - if (node && typeof node === "object" && "props" in node) { - return extractText(node.props.children); + if ( + React.isValidElement(node) && + node.props && + typeof node.props === "object" && + "children" in node.props + ) { + return extractText(node.props.children as React.ReactNode); } return ""; } export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) { let className: string | undefined = undefined; + const child = props.children as React.ReactElement<{ className?: string; children?: React.ReactNode }> | undefined; if ( - props.children && - typeof props.children === "object" && - "props" in props.children && - props.children && - typeof (props.children as any).props === "object" && - (props.children as any).props.className + child && + typeof child === "object" && + "props" in child && + child.props.className ) { - className = (props.children as any).props.className as string | undefined; + className = child.props.className as string | undefined; } let language = ""; if (className) { @@ -32,12 +37,11 @@ export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) } let codeContent = ""; if ( - props.children && - typeof props.children === "object" && - "props" in props.children && - (props.children as any).props + child && + typeof child === "object" && + "props" in child ) { - codeContent = extractText((props.children as any).props.children); + codeContent = extractText(child.props.children); } function handleCopy(e: React.MouseEvent) {