fix: copy button not work
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user