Install firstyarn add clipboard
The demo is as follows
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>
</>
}
There is also the implementation of the js native version quoted from the original link: https://blog.csdn.net/weixin_38629529/article/details/114918057
const copyToClipboard = (value) => {
const textarea = document.createElement('textarea');
textarea.value = value;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。