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

当前回答

import React, { Component } from 'react';

export default class CopyTextOnClick extends Component {
    copyText = () => {
        this.refs.input.select();

        document.execCommand('copy');

        return false;
    }

    render () {
        const { text } = this.state;

        return (
            <button onClick={ this.copyText }>
                { text }

                <input
                    ref="input"
                    type="text"
                    defaultValue={ text }
                    style={{ position: 'fixed', top: '-1000px' }} />
            </button>
        )
    }
}

其他回答

首先创建BTN,然后添加这个onClick:

onClick={() =>  navigator.clipboard.writeText(textState)}

or

onClick={() =>  navigator.clipboard.writeText('Your text for copy')}

最简单的方法是使用react-copy-to-clipboard npm包。

您可以使用以下命令安装它

npm install --save react react-copy-to-clipboard

请按照以下方式使用它。

const App = React.createClass({
  getInitialState() {
    return {value: '', copied: false};
  },


  onChange({target: {value}}) {
    this.setState({value, copied: false});
  },


  onCopy() {
    this.setState({copied: true});
  },


  render() {
    return (
      <div>

          <input value={this.state.value} size={10} onChange={this.onChange} />

        <CopyToClipboard text={this.state.value} onCopy={this.onCopy}>
          <button>Copy</button>
        </CopyToClipboard>

                <div>
        {this.state.copied ? <span >Copied.</span> : null}
                </div>
        <br />

        <input type="text" />

      </div>
    );
  }
});

ReactDOM.render(<App />, document.getElementById('container'));

以下链接提供了详细的解释

https://www.npmjs.com/package/react-copy-to-clipboard

这是一把移动小提琴。

找到了最好的方法。我是说最快的方法:w3school

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

在react函数组件中。创建名为handleCopy的函数:

function handleCopy() {
  // get the input Element ID. Save the reference into copyText
  var copyText = document.getElementById("mail")
  // select() will select all data from this input field filled  
  copyText.select()
  copyText.setSelectionRange(0, 99999)
  // execCommand() works just fine except IE 8. as w3schools mention
  document.execCommand("copy")
  // alert the copied value from text input
  alert(`Email copied: ${copyText.value} `)
}

<>
              <input
                readOnly
                type="text"
                value="exemple@email.com"
                id="mail"
              />
              <button onClick={handleCopy}>Copy email</button>

</>

如果不使用React, w3schools也有一个很酷的方法来做到这一点,工具提示包括:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard2

如果使用React,一个很酷的想法是:使用Toastify提醒消息。 https://github.com/fkhadra/react-toastify这是一个很容易使用的库。 安装后,你可以更改这一行:

 alert(`Email copied: ${copyText.value} `)

比如:

toast.success(`Email Copied: ${copyText.value} `)

如果你想使用它,不要忘记安装toastify。导入ToastContainer,同时也导入css:

import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"

并将烤面包的容器放入里面返回。

import React from "react"

import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"


export default function Exemple() {
  function handleCopy() {
    var copyText = document.getElementById("mail")
    copyText.select()
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy")
    toast.success(`Hi! Now you can: ctrl+v: ${copyText.value} `)
  }

  return (
    <>
      <ToastContainer />
      <Container>
                <span>E-mail</span>
              <input
                readOnly
                type="text"
                value="myemail@exemple.com"
                id="mail"
              />
              <button onClick={handleCopy}>Copy Email</button>
      </Container>
    </>
  )
}

你的代码应该工作完美,我用同样的方式。只需要确保如果click事件是从弹出屏幕中触发的,比如bootstrap模式或其他,创建的元素必须在该模式中,否则它不会被复制。您总是可以给出该模式中元素的id(作为第二个参数),并使用getElementById检索它,然后将新创建的元素附加到该元素而不是文档。就像这样:

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);
}

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

<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>