前言:
最近在公司研发后台系统,用户反馈在双击某些信息时希望可以进行复制的操作,多处使用进而封装为组件
首先:安装copy-to-clipboard
npm i --save copy-to-clipboard
其次:封装组件
import React, { memo, useCallback } from 'react';
import { notification } from "antd";
import copy from 'copy-to-clipboard';
const [api, contextHolder] = notification.useNotification();
const Copy = memo((props) => {
const { txt, children } = props;
const copyTxt = useCallback(() => {
if (copy(txt)) {
api.success({ message: '已复制' });
} else {
api.warning({ message: '复制失败' });
}
}, [txt])
return <span style={{cursor:'pointer'}} onDoubleClick={copyTxt}>
{children}
</span>
})
export default Copy
最后,使用:
import Copy from "../../Copy";
const UseCopy = () =>{
let name = "蓝宇逸尘"
return(
<Copy txt={name}>
{name}
</Copy>
)
}
export default UseCopy