react hook 使用clipboard.js 复制文本

clipboard.js git 地址

先安装
yarn add clipboard

demo如下

import React, {  useRef, useEffect, useState } from 'react';
import ClipboardJS from 'clipboard';

const Demo : React.FC = () => {
    const copyBtnRef = useRef(null)
    const [text, setText] = useState('https://segmentfault.com/u/yolo_y')

    let clipboard: any
    useEffect(() => {
        if(copyBtnRef.current) {
            clipboard = new ClipboardJS(copyBtnRef.current,{
                text: () => text
            });

            clipboard.on('success', function(e:any) {
                console.log('copy success')
            })
        }
        return () => clipboard?.destroy && clipboard.destroy();
    }, [copyBtnRef, text]);

    return <>
        
{text}
copy
{setText('https://segmentfault.com/a/1190000015303823')}}>change Text
}

还有js原生版本的实现 引用自 原文链接:https://blog.csdn.net/weixin_...

const copyToClipboard = (value) => {
   const textarea = document.createElement('textarea');
   textarea.value = value;
   document.body.appendChild(textarea);
   textarea.select();
   document.execCommand('copy');
   document.body.removeChild(textarea);
}

你可能感兴趣的:(react hook 使用clipboard.js 复制文本)