In reactJS, how to copy text to clipboard?

前端 未结 21 1867
刺人心
刺人心 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条回答
  • 2020-12-02 05:22
    <input
    value={get(data, "api_key")}
    styleName="input-wrap"
    title={get(data, "api_key")}
    ref={apikeyObjRef}
    />
      <div
    onClick={() => {
      apikeyObjRef.current.select();
      if (document.execCommand("copy")) {
        document.execCommand("copy");
      }
    }}
    styleName="copy"
    >
      复制
    </div>
    
    0 讨论(0)
  • 2020-12-02 05:25

    Your code should work perfectly, I use it the same way. Only make sure that if the click event is triggered from within a pop up screen like a bootstrap modal or something, the created element has to be within that modal otherwise it won't copy. You could always give the id of an element within that modal (as a second parameter) and retrieve it with getElementById, then append the newly created element to that one instead of the document. Something like this:

    copyToClipboard = (text, elementId) => {
      const textField = document.createElement('textarea');
      textField.innerText = text;
      const parentElement = document.getElementById(elementId);
      parentElement.appendChild(textField);
      textField.select();
      document.execCommand('copy');
      parentElement.removeChild(textField);
    }
    
    0 讨论(0)
  • 2020-12-02 05:25

    Here's another use case, if you would like to copy the current url to your clipboard:

    Define a method

    const copyToClipboard = e => {
      navigator.clipboard.writeText(window.location.toString())
    }
    

    Call that method

    <button copyToClipboard={shareLink}>
       Click to copy current url to clipboard
    </button>
    
    0 讨论(0)
提交回复
热议问题