In reactJS, how to copy text to clipboard?

前端 未结 21 1947
刺人心
刺人心 2020-12-02 04:43

I\'m using ReactJS and when a user clicks a link I want to copy some text to the clipboard.

I am using Chrome 52 and I do not need to support any other browsers.

21条回答
  •  Happy的楠姐
    2020-12-02 05:05

    I personally don't see the need for a library for this. Looking at http://caniuse.com/#feat=clipboard it's pretty widely supported now, however you can still do things like checking to see if the functionality exists in the current client and simply hide the copy button if it doesn't.

    import React from 'react';
    
    class CopyExample extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = { copySuccess: '' }
      }
    
      copyToClipboard = (e) => {
        this.textArea.select();
        document.execCommand('copy');
        // This is just personal preference.
        // I prefer to not show the whole text area selected.
        e.target.focus();
        this.setState({ copySuccess: 'Copied!' });
      };
    
      render() {
        return (
          
    { /* Logical shortcut for only displaying the button if the copy command exists */ document.queryCommandSupported('copy') &&
    {this.state.copySuccess}
    }