关于react.js:react-hook-使用clipboardjs-复制文本

42次阅读

共计 930 个字符,预计需要花费 3 分钟才能阅读完成。

clipboard.js git 地址

先装置
yarn add clipboard

demo 如下

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

const Demo : React.FC<any> = () => {const copyBtnRef = useRef<any>(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 <>
        <div>{text}</div>
        <div ref={copyBtnRef}>copy</div>
        <div onClick={() => {setText('https://segmentfault.com/a/1190000015303823')}}>change Text</div>
    </>
}

还有 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);
}

正文完
 0