我使用的是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()
}

当前回答

如果希望从DIV而不是文本字段中进行选择,下面是代码。“代码”是需要复制的值

import React from 'react'
class CopyToClipboard extends React.Component {

  copyToClipboard(code) {
    var textField = document.createElement('textarea')
    textField.innerText = code
    document.body.appendChild(textField)
    textField.select()
    document.execCommand('copy')
    textField.remove()
  }
  render() {
    return (
      <div onClick={this.copyToClipboard.bind(this, code)}>
        {code}
      </div>

    )
  }
}

export default CopyToClipboard

其他回答

您可以使用事件clipboardData收集方法e.clipboardData。setData(类型、内容)。

在我看来,这是实现在剪贴板内推送一些东西的最直接的方法,看看这个(我用它来修改数据,而本地复制动作):

...

handleCopy = (e) => {
    e.preventDefault();
    e.clipboardData.setData('text/plain', 'Hello, world!');
}

render = () =>
    <Component
        onCopy={this.handleCopy}
    />

我选择了这个路径:https://developer.mozilla.org/en-US/docs/Web/Events/copy

干杯!

编辑:出于测试目的,我添加了代码依赖:https://codepen.io/dprzygodzki/pen/ZaJMKb

你可以做到这一点,而不需要一个外部库,例如:在一个按钮

<button 
  onClick={() =>  navigator.clipboard.writeText('Copy this text to clipboard')}
>
  Copy
</button>

对于ie11和更老的浏览器,你可能需要稍微改变一下代码,这里有一个例子:

<button 
  onClick={() =>  window.clipboardData.setData("Text", 'Copy this text to clipboard')}>
 Copy
</button>

这对我来说很有用:

const handleCopyLink = useCallback(() => {
    const textField = document.createElement('textarea')
    textField.innerText = url
    document.body.appendChild(textField)
    if (window.navigator.platform === 'iPhone') {
      textField.setSelectionRange(0, 99999)
    } else {
      textField.select()
    }
    document.execCommand('copy')
    textField.remove()
  }, [url])

您可以使用useRef选择元素中的文本,然后将其复制到剪贴板

import React, { useRef } from "react";

const Comp = () => {
   const copyTxt = useRef();

   const handleCopyTxt = () => {
   let txtDiv = copyTxt.current;
      if (document.selection) {
        // IE
        var range = document.body.createTextRange();
        range.moveToElementText(txtDiv);
        range.select();
      } else if (window.getSelection) {
        // other browsers
        var range = document.createRange();
        range.selectNode(txtDiv);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
      }
      document.execCommand("copy");
    }

    return ( <div ref={copyTxt} > some text to copied </div> )
}

使用材质UI完全工作的React组件

为了更好地理解,我还准备了一个CodeSandbox。希望这能有所帮助。

import { useState } from "react";
import { IconButton, Snackbar } from "@mui/material";
import ShareIcon from "@mui/icons-material/Share";

const CopyToClipboardButton = () => {
  const [open, setOpen] = useState(false);

  const handleClick = () => {
    setOpen(true);
    navigator.clipboard.writeText(window.location.toString());
  };

  return (
    <>
      <IconButton onClick={handleClick} color="primary">
        <ShareIcon />
      </IconButton>
      <Snackbar
        message="Copied to clibboard"
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        autoHideDuration={20000}
        onClose={() => setOpen(false)}
        open={open}
      />
    </>
  );
};

export default CopyToClipboardButton;

下面是按钮的样子:

当你点击它时:

来源:https://fwuensche.medium.com/react——按钮——复制到剪贴板- 75 ef5ecdc708