forgeplus-react/src/forge/Component/CopyTool.jsx

51 lines
1.4 KiB
React
Raw Normal View History

import React, { useState, useCallback, memo } from 'react';
import { Tooltip } from 'antd';
CopyTool.defaultProps = {
2021-09-06 13:46:06 +08:00
beforeText: '复制链接', //浮动过去显示的文字
afterText: '复制成功', //点击后显示的文字
className: '', //传给svg的class
inputId: 'copyText', //要复制的文本的ID
2021-09-03 17:14:45 +08:00
timeOut:true, //复制后将浮动的文字改为beforeText
};
2021-08-31 11:18:01 +08:00
function CopyTool({ beforeText, afterText, className , inputId , timeOut }) {
const [title, setTitle] = useState(() => {
return beforeText;
});
// 复制链接
const copyUrl = useCallback(() => {
2021-08-31 11:18:01 +08:00
const copyEle = document.querySelector(`#${inputId}`); // 获取要复制的节点
if (!copyEle) {
console.error("您的CopyTool未设置正确的inputId");
return;
}
2021-09-03 17:14:45 +08:00
copyEle.select(); // 执行选中元素
if (document.execCommand('copy')) {
document.execCommand('copy');
}
2021-09-10 11:47:48 +08:00
document.getSelection().removeAllRanges();
2021-09-03 17:14:45 +08:00
setTitle(afterText);
2021-08-31 11:18:01 +08:00
if(timeOut){
setTimeout(function(){
setTitle(beforeText);
},1500)
}
}, []);
return (
<Tooltip
placement="top"
title={title}
onVisibleChange={() => { setTitle(beforeText) }}
>
<i className={`iconfont icon-fuzhiicon ${className}`} style={{ color: '#466aff' }} onClick={copyUrl}></i>
</Tooltip>
);
}
export default memo(CopyTool);