fix: copyToClipboard button not work

This commit is contained in:
ReaJason
2024-12-31 11:41:08 +08:00
parent 2ec43d97dd
commit 717c81571b
4 changed files with 29 additions and 24 deletions
+15 -15
View File
@@ -2,6 +2,7 @@ import { Button, ButtonProps } from "@/components/ui/button.tsx";
import { cn } from "@/lib/utils.ts";
import { CheckIcon, ClipboardIcon } from "lucide-react";
import { HTMLProps, useEffect, useState } from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { materialDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { toast } from "sonner";
@@ -11,10 +12,6 @@ interface CopyButtonProps extends ButtonProps {
src?: string;
}
export function copyToClipboardWithMeta(value: string) {
navigator.clipboard.writeText(value);
}
export function CopyButton({ value, className, src, variant = "ghost", ...props }: CopyButtonProps) {
const [hasCopied, setHasCopied] = useState(false);
@@ -27,21 +24,24 @@ export function CopyButton({ value, className, src, variant = "ghost", ...props
}, [hasCopied]);
return (
<Button
size="icon"
type="button"
variant={variant}
className={cn("relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50", className)}
onClick={() => {
copyToClipboardWithMeta(value);
<CopyToClipboard
text={value}
onCopy={() => {
setHasCopied(true);
toast.success("复制成功");
}}
{...props}
>
<span className="sr-only">Copy</span>
{hasCopied ? <CheckIcon /> : <ClipboardIcon />}
</Button>
<Button
size="icon"
type="button"
variant={variant}
className={cn("relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50", className)}
{...props}
>
<span className="sr-only">Copy</span>
{hasCopied ? <CheckIcon /> : <ClipboardIcon />}
</Button>
</CopyToClipboard>
);
}
+6 -3
View File
@@ -2,6 +2,7 @@ import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Check, Copy } from "lucide-react";
import { useCallback, useState } from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import { toast } from "sonner";
interface CopyableFieldProps {
@@ -31,9 +32,11 @@ export function CopyableField({ label, value, size }: CopyableFieldProps) {
{value} {size != null && `(${size} bytes)`}
</p>
</div>
<Button variant="ghost" size="icon" type="button" onClick={copyToClipboard}>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
<CopyToClipboard text={value as string} onCopy={copyToClipboard}>
<Button variant="ghost" size="icon" type="button">
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</CopyToClipboard>
</div>
);
}