在reactJS中,如何将文本复制到剪贴板? [英] In reactJS, how to copy text to clipboard?

查看:1048
本文介绍了在reactJS中,如何将文本复制到剪贴板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJS,并且当用户单击链接时,我要将一些文本复制到剪贴板。

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

我正在使用Chrome 52,不需要来支持其他任何浏览器。

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

我不明白为什么这段代码不会将数据复制到剪贴板。 (代码段的来源来自Reddit帖子。)

I can't see why this code does not result in the data being copied to the clipboard. (the origin of the code snippet is from a Reddit post).

我做错了吗?有人可以建议使用 reactjs实现复制到剪贴板的正确方法吗?

Am I doing this wrong? Can anyone suggest is there a "correct" way to implement copy to clipboard using reactjs?

copyToClipboard = (text) => {
  console.log('text', text)
  var textField = document.createElement('textarea')
  textField.innerText = text
  document.body.appendChild(textField)
  textField.select()
  document.execCommand('copy')
  textField.remove()
}


推荐答案

我个人认为不需要为此提供库。在 http://caniuse.com/#feat=clipboard 上,它得到了广泛的支持,但是您仍然可以执行诸如检查当前客户端中是否存在该功能的操作,并简单地隐藏复制按钮(如果不存在)。

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 (
      <div>
        {
         /* Logical shortcut for only displaying the 
            button if the copy command exists */
         document.queryCommandSupported('copy') &&
          <div>
            <button onClick={this.copyToClipboard}>Copy</button> 
            {this.state.copySuccess}
          </div>
        }
        <form>
          <textarea
            ref={(textarea) => this.textArea = textarea}
            value='Some text to copy'
          />
        </form>
      </div>
    );
  }

}
    
export default CopyExample;

更新:在React 16.7.0-alpha.0中使用React Hooks重写

import React, { useRef, useState } from 'react';

export default function CopyExample() {

  const [copySuccess, setCopySuccess] = useState('');
  const textAreaRef = useRef(null);

  function copyToClipboard(e) {
    textAreaRef.current.select();
    document.execCommand('copy');
    // This is just personal preference.
    // I prefer to not show the whole text area selected.
    e.target.focus();
    setCopySuccess('Copied!');
  };

  return (
    <div>
      {
       /* Logical shortcut for only displaying the 
          button if the copy command exists */
       document.queryCommandSupported('copy') &&
        <div>
          <button onClick={copyToClipboard}>Copy</button> 
          {copySuccess}
        </div>
      }
      <form>
        <textarea
          ref={textAreaRef}
          value='Some text to copy'
        />
      </form>
    </div>
  );
}

这篇关于在reactJS中,如何将文本复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆