简体   繁体   English

将p标签之间的文本复制到React中的剪贴板

[英]Copy text between p tags to clipboard in React

I am trying to create copy to Clipboard Component. 我正在尝试创建副本到剪贴板组件。 Here is my code: 这是我的代码:

import React from 'react';
import logo from './logo.svg';
import './App.css';

class CopyClipboard extends React.Component {

  constructor(props) {
    super(props);

    this.state = { copySuccess: 'Copy to Clipboard!' }
  }

  copyToClipboard = (e) => {

    this.textContent.select();
    document.execCommand('copy');
    e.target.focus();
    this.setState({ copySuccess: 'Copied to Clipboard!' });
  };

  render() {
    return (
      <div class="positioning">
        {
           //if i need
        }

          <p onClick={this.copyToClipboard} ref={(c) => (this.textContent = c)}>yotam@gmail.com</p>
        <div class="success">{this.state.copySuccess}</div>
      </div>
    );
  }

}

export default CopyClipboard;

I get Parsing error: Unexpected token error. 我收到Parsing error: Unexpected token错误。 But if i use input tag then its work fine. 但是,如果我使用input标签,则其工作正常。 Where i have done wrong? 我做错了什么?

For p tag, you can't use .select . 对于p标签,您不能使用.select

You need to use selectNode and addRange 您需要使用selectNodeaddRange

Try something like this for the selection function 尝试类似这样的选择功能

copyToClipboard = async e => {
  window.getSelection().removeAllRanges();
  var range = document.createRange();
  range.selectNode(this.textContent);
  window.getSelection().addRange(range);
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  this.setState({ copied: true });
};

Click here for a working example too 单击此处也是一个可行的示例

Also check out this answer to select text between non input tags. 另外, 请查看此答案以在非输入标签之间选择文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM