You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何用一个按钮同时复制两个值?

Solution: Copy Both Values with a Single Button

No problem at all! Since you're already using copy-to-clipboard and Reactstrap's Button, merging the two copy actions into one is super simple. Here's how to do it:

Step-by-Step Implementation

First, create a function that combines both playerID and eventId into a single string (you can adjust the formatting to whatever works best for your use case—newline, comma-separated, etc.), then use the copy method to send that combined string to the clipboard.

Here's a complete code example:

import { Button } from 'reactstrap';
import copy from 'copy-to-clipboard';

// Example component (adjust based on your existing setup)
const PlayerEventCopyButton = ({ player }) => {
  const handleCopyBoth = () => {
    // Guard clause to avoid errors if player/general is undefined
    if (!player?.general) {
      alert('No player or event data available to copy!');
      return;
    }

    // Combine the two values—customize the separator to your needs
    const combinedContent = `${player.general.playerID}\n${player.general.eventId}`;
    
    // Copy to clipboard
    const didCopy = copy(combinedContent);
    
    // Optional: Confirm success to the user
    if (didCopy) {
      alert('Player ID and Event ID copied to clipboard!');
    } else {
      alert('Oops, failed to copy. Try again!');
    }
  };

  return (
    <Button onClick={handleCopyBoth} color="primary">
      Copy Player ID & Event ID
    </Button>
  );
};

export default PlayerEventCopyButton;

Key Notes:

  • Formatting Flexibility: Swap out the \n (newline) for something else if you prefer—like , (comma + space) or | (pipe separator) depending on how you want the copied text to look.
  • Error Handling: The guard clause checks if player.general exists to prevent runtime errors if the data isn't loaded yet.
  • Success Feedback: The copy function returns a boolean, so you can use that to show a success/error message to the user (alert is just a simple example—you could use a toast component for a cleaner UI).

内容的提问来源于stack exchange,提问作者KBball

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:10:31