首页 > 解决方案 > 在 React 中使用 document.createRange 和 window.getSelection

问题描述

我正在使用 Reactjs。在 React中如何使用document.createRange以及在 React 中如何使用?window.getSelectiondocument.execCommand('copy')

我想复制我的 html 表格的内容。所以我使用了代码

copyTable(e){
        let elTable = this.tableElement.current.localName\\ elTable= "table"     
  this.copyData(elTable)
    }

    copyData(elToBeCopied){

        let range, sel;

  // Ensure that range and selection are supported by the browsers
  if (document.createRange && window.getSelection) {

    range = document.createRange();
    sel = window.getSelection();
    // unselect any element in the page
    sel.removeAllRanges();

    try {
      range.selectNodeContents(elToBeCopied);
      sel.addRange(range);
    } catch (e) {
      range.selectNode(elToBeCopied);
      sel.addRange(range);
    }

    document.execCommand('copy');
  }

  sel.removeAllRanges();

  console.log('Element Copied! Paste it in a file')


    }

我通过在我的 html 表中elTable创建一个来获得价值。ref

调试时,调试器正在进入功能 copyData

但不能从表中复制数据。为什么?

我正在使用反应 js。

标签: reactjs

解决方案


在 App.js 中使用以下内容render() method

console.log(window.getSelection());
console.log(document.createRange());

在控制台中给出结果:

在此处输入图像描述

您是否尝试过使用它们?如果您将代码显示在不起作用的地方并且我们可以从那里开始,这可能会有所帮助。


推荐阅读