创建一个CopyText组件,添加a标签点击时把传入的text值复制到粘贴板,并设置Copy的状态:
CopyText.tsx

import { Space } from 'antd';
import React, { useCallback, useState } from 'react';

export interface ICopyTextProps  {
    text: string;
}

export const CopyText: React.FC<ICopyTextProps> = (props) => {

    const text = props.text;

    const [isCopied, setIsCopied] = useState(false);

    const handleClick = useCallback( () => {

        const input = document.createElement('input');
        input.setAttribute('readonly', 'readonly');
        input.setAttribute('value', text);
        document.body.appendChild(input);
        input.setSelectionRange(0, 9999);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        setIsCopied(true);
    }, [text]);

    return (
        <Space>
            <a
                style={{'wordBreak': 'keep-all'}}
                onClick={ handleClick }
            >
                {isCopied? 'Copied' : 'Copy'}
            </a>
        </Space>

    );

};

创建一个input元素把传入的text放入input中,最后input.setSelectionRange(0, 9999); document.execCommand('copy')进行复制。

使用

例如在antd Table的render中:

render: (d) => {
    return <div>{d.address}  <CompCopyText text={ d.address } /></div>;
},

洛阳醉长安行
57 声望3 粉丝

charging...