React中如何用一个按钮同时复制两个值?
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.generalexists to prevent runtime errors if the data isn't loaded yet. - Success Feedback: The
copyfunction 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
相关产品推荐
相关产品推荐

