如何将div内容以字符串格式复制到剪贴板

时间:2019-07-09 09:27:55

标签: javascript reactjs

我正在使用ReactJS,当用户单击按钮时,我想将一些div内容复制到剪贴板。

我看不到为什么这段代码不会导致数据被复制到剪贴板。 真正满足div

的内容时,就可以从redux存储中获得价值
componentDidUpdate(prevProps, prevState, snapshot) {
  console.log("value to copy is-->", this.props.copy);
  var copyText = document.getElementById("myInput");

  /* Select the text field */

  console.log("copyText-->", copyText);
  console.log("document-->", document);
  /* Copy the text inside the text field */
  document.execCommand("copy");
}

2 个答案:

答案 0 :(得分:1)

您需要在运行复制命令之前添加el.select();

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("value to copy is-->",this.props.copy);
    var copyText = document.getElementById("myInput");

    /* Select the text field */

    copyText.select();

    /* Copy the text inside the text field */
    document.execCommand("copy");
}

答案 1 :(得分:0)

您可以使用this package。这非常简单,可以跨平台工作。