我使用的是ReactJS,当用户点击一个链接时,我想复制一些文本到剪贴板。

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

我不明白为什么这段代码没有导致数据被复制到剪贴板。(代码片段的来源是Reddit的一篇帖子)。

我做错了吗?谁能建议有一个“正确”的方法来实现复制到剪贴板使用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()
}

当前回答

你也可以在函数组件或无状态组件中使用react钩子: PS:确保你通过npm/yarn使用这个命令安装useClippy: NPM安装使用clippy或 纱线添加使用夹头

import React from 'react';
import useClippy from 'use-clippy';

export default function YourComponent() {

// clipboard is the contents of the user's clipboard.
  // setClipboard('new value') wil set the contents of the user's clipboard.

  const [clipboard, setClipboard] = useClippy();

  return (
    <div>

      {/* Button that demonstrates reading the clipboard. */}
      <button
        onClick={() => {
          alert(`Your clipboard contains: ${clipboard}`);
        }}
      >
        Read my clipboard
      </button>

      {/* Button that demonstrates writing to the clipboard. */}
      <button
        onClick={() => {
          setClipboard(`Random number: ${Math.random()}`);
        }}
      >
        Copy something
      </button>
    </div>
  );
}

其他回答

剪贴板将在2021年得到各大浏览器的良好支持。一种方法是首先构建剪贴板函数的副本,然后使用onClick事件处理程序调用它。

function copy(text){
  navigator.clipboard.writeText(text)
}

为了防止硬编码,让我们假设字符串被分配给一个名为someText的变量

<span onClick={() => copy(someText)}>
  {someText}
</span>

针对React开发者

 const preventCopyPasteBody = (state) => {
       document.addEventListener(state, (evt) => {
      if (evt.target.id === 'body') {
             evt.preventDefault();
           return false;
          }
        return false;
       }, false);
      }

 preventCopyPasteBody ("contextmenu")
 preventCopyPasteBody ("copy")
 preventCopyPasteBody ("paste")
 preventCopyPasteBody ("cut")

<Typography id="body" variant="body1"  component="div" className={classes.text} style={{ fontSize: fontSize }}>{story}</Typography>
const handleCopy = async () => {
    let copyText = document.getElementById('input') as HTMLInputElement;
    copyText.select();
    document.execCommand('copy');
  };

return (
  <TextField
     variant="outlined"
     value={copyText}
     id="input" 
  />
);

这是我的工作。

如果您希望以编程方式将数据写入剪贴板,可以在按钮上使用这个简单的内联onClick函数。

onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}

无需安装第三方软件包。我尽量让它简单。这对我来说很有效。

import React, { useState } from "react"    
function MyApp() {
    const [copySuccess, setCopySuccess] = useState(null);
    const copyToClipBoard = async copyMe => {
       try {
           await navigator.clipboard.writeText(copyMe);
           setCopySuccess('Copied!');
       } 
       catch (err) {
           setCopySuccess('Failed to copy!');
       }
    };
     
    return (
        <button onClick={(e) => copyToClipBoard(what you want to copy goes here)} >
           My button
        </button>    
       )
    }