跳转到内容
按钮·免费

复制按钮(React)

用 React 和 TypeScript 写的按钮,把一段文字复制到剪贴板。按钮文字会显示“Copied”两秒,隐藏的状态行会告诉读屏软件。不需要任何 CSS 框架;在用普通 http 提供的页面上,它会改用旧的复制命令。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

CopyButton.tsx · 112 行
import { useEffect, useRef, useState, type ButtonHTMLAttributes, type CSSProperties } from 'react';

// React button that copies a text to the clipboard and tells the user it worked.
// No CSS framework: it takes the text colour of its parent; pass className or style to restyle it.
// <CopyButton text={inviteLink} />
// <CopyButton text={code}>Copy code</CopyButton>
//
// The label changes to "Copied" for two seconds and a hidden status line tells screen readers.
// Over plain http (no secure context) the Clipboard API is missing, so it falls back to a hidden textarea.

type Status = 'idle' | 'copied' | 'failed';

export interface CopyButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> {
  /** What goes to the clipboard. */
  text: string;
  /** How long "Copied" stays on the button, in milliseconds. */
  resetAfterMs?: number;
  /** Called after a successful copy, for analytics or a toast. */
  onCopied?: () => void;
}

const baseStyle: CSSProperties = {
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  minWidth: 44,
  minHeight: 44,
  padding: '8px 16px',
  border: '1px solid currentColor',
  borderRadius: 8,
  background: 'transparent',
  color: 'inherit',
  font: 'inherit',
  fontWeight: 600,
  cursor: 'pointer',
};

const visuallyHidden: CSSProperties = {
  position: 'absolute',
  width: 1,
  height: 1,
  margin: -1,
  padding: 0,
  overflow: 'hidden',
  clip: 'rect(0 0 0 0)',
  whiteSpace: 'nowrap',
  border: 0,
};

export function CopyButton({
  text,
  resetAfterMs = 2000,
  onCopied,
  children = 'Copy',
  type = 'button',
  style,
  ...rest
}: CopyButtonProps) {
  const [status, setStatus] = useState<Status>('idle');
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  // Do not leave a timer running after the button is gone.
  useEffect(() => () => clearTimeout(timer.current), []);

  async function handleClick() {
    clearTimeout(timer.current);
    try {
      await copyText(text);
      setStatus('copied');
      onCopied?.();
    } catch {
      setStatus('failed');
    }
    timer.current = setTimeout(() => setStatus('idle'), resetAfterMs);
  }

  const label = status === 'copied' ? 'Copied' : status === 'failed' ? 'Copy failed' : children;
  const announcement =
    status === 'copied'
      ? 'Copied to the clipboard'

此预览已截短。安装后可获得完整内容。

1.0.0 的变更

首个版本。

相关