在React中将HTML表格复制到剪贴板

3

我在我的React项目中有一个HTML表格。我想将该表格复制到剪贴板。

原始答案:Original Answer

<table id="sample">
 <thead>
  <th>Amount</th>
  <th>Charges</th>
 </thead>

 <tbody>
   <tr>{item.Amount}</tr>
   <tr>{item.Charges}</tr>
 </tbody>
</table>

这是表格结构。我没有包含任何React代码。
我参考了这个示例代码https://stackblitz.com/edit/js-copy-element?file=index.js。但它不是用React写的。
如何使用React代码将表格复制到剪贴板?原始答案:最初的回答。
1个回答

9
可能已经有点晚回答了,但这是我是如何做到的。
我在组件的渲染函数中呈现了一个元素。
render(){
    return(
        <table id="table">
         .... your table content
        </table>
    )
}

只需参考上面分享的示例代码,就可以简单地构建一个复制函数。

copyTable = () => {
const elTable = document.querySelector('table');

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(elTable);
    sel.addRange(range);
  } catch (e) {
    range.selectNode(elTable);
    sel.addRange(range);
  }

  document.execCommand('copy');
}

sel.removeAllRanges();

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

然后,通过构建类似以下元素的方式调用此函数:

<h1 onClick={()=>{this.copyTable()}}>Copy to table</h1>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接