import React from 'react';
function oldSchoolCopy(text: string) {
const tempTextArea = document.createElement('textarea');
tempTextArea.value = text;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
}
export default function useCopyToClipboard(): [string | null, (text: string) => Promise<void>] {
const [state, setState] = React.useState<string | null>(null);
const copyToClipboard = React.useCallback(async (value: string) => {
try {
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(value);
setState(value);
} else {
throw new Error('writeText not supported');
}
} catch (e) {
oldSchoolCopy(value);
setState(value);
}
}, []);
return [state, copyToClipboard];
}
复制到剪贴板功能的React Hooks实现
于 2024-01-17 11:17:25 首次发布