fix: copy button not work

This commit is contained in:
jialin
2024-07-19 18:48:15 +08:00
parent b48be3b883
commit 3842006f6e
6 changed files with 78 additions and 44 deletions
+35 -7
View File
@@ -1,6 +1,8 @@
import useCopyToClipboard from '@/hooks/use-copy-to-clipboard';
import { CheckCircleFilled, CopyOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import ClipboardJS from 'clipboard';
import { useEffect, useRef, useState } from 'react';
type CopyButtonProps = {
text: string;
@@ -21,19 +23,45 @@ const CopyButton: React.FC<CopyButtonProps> = ({
style,
size = 'middle'
}) => {
const { copied, copyToClipboard } = useCopyToClipboard();
const intl = useIntl();
const [copied, setCopied] = useState(false);
const buttonRef = useRef(null);
const clipboardRef = useRef<any>(null);
const handleCopy = async (e: any) => {
e.stopPropagation();
await copyToClipboard(text);
const initClipboard = () => {
if (buttonRef.current) {
clipboardRef.current = new ClipboardJS(buttonRef.current);
clipboardRef.current.on('success', () => {
setCopied(true);
setTimeout(() => {
setCopied(false);
}, 3000);
});
clipboardRef.current.on('error', (e: any) => {
message.success(
intl.formatMessage({ id: 'common.copy.fail' }) as string
);
e.clearSelection();
});
}
};
useEffect(() => {
initClipboard();
return () => {
clipboardRef.current?.destroy();
};
}, [buttonRef]);
return (
<Button
ref={buttonRef}
type={type}
shape={shape}
size={size}
onClick={handleCopy}
disabled={!!disabled}
data-clipboard-text={text}
icon={
copied ? (
<CheckCircleFilled