背景:业务上对于一些长文本,或者特定的文案需要给予一键复制的功能
实现效果:
实现原理
import { Button, Popover } from 'antd'
import copy from 'copy-to-clipboard'
import React, { useMemo } from 'react'
// 复制组件
import Message from '@/components/antd/Message'
interface CopyToClipType {
text: any // 展示的内容 通常为订单号等
copyText?: string // 复制文案 默认复制
successCoptText?: string // 复制成功文案
children?: JSX.Element | string
}
const CopyToClip: React.FC<CopyToClipType> = (properties) => {
const {
text,
copyText = '复制',
successCoptText = '已成功复制到粘贴板!',
children,
...setting
} = properties
const Content = useMemo(() => {
return (
<Button
type="link"
onClick={(e) => {
// 注意阻止冒泡因人而异,小编的业务场景是需要点击单号跳转到详情页(但是复制按钮会触发单号的点击事件)
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
copy(text)
void Message.success(successCoptText)
}}
>
{copyText}
</Button>
)
}, [copyText, successCoptText, text])
return (
<>
{/* Popover为ant的气泡卡片 */}
<Popover trigger="hover" {...setting} content={Content}>//
{children || text}
</Popover>
</>
)
}
export default React.memo(CopyToClip)
结尾:文中出现思考不足或者错误的地方,欢迎指正。