In reactJS, how to copy text to clipboard?

前端 未结 21 1972
刺人心
刺人心 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条回答
  •  旧时难觅i
    2020-12-02 05:12

    For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:

         import React from 'react';
         ....
    
        //set ref to your div
              setRef = (ref) => {
                // debugger; //eslint-disable-line
                this.dialogRef = ref;
              };
    
              createMarkeup = content => ({
                __html: content,
              });
    
        //following function select and copy data to the clipboard from the selected Div. 
       //Please note that it is only tested in chrome but compatibility for other browsers can be easily done
    
              copyDataToClipboard = () => {
                try {
                  const range = document.createRange();
                  const selection = window.getSelection();
                  range.selectNodeContents(this.dialogRef);
                  selection.removeAllRanges();
                  selection.addRange(range);
                  document.execCommand('copy');
                  this.showNotification('Macro copied successfully.', 'info');
                  this.props.closeMacroWindow();
                } catch (err) {
                  // console.log(err); //eslint-disable-line
                  //alert('Macro copy failed.');
                }
              };
    
                  render() {
                        return (
                            
    { this.dialogRef = el; }} // className={classes.paper} dangerouslySetInnerHTML={this.createMarkeup(this.props.content)} /> ); }

提交回复
热议问题