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

Jan*_*red 3 html-table reactjs

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

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

 <tbody>
   <tr>{item.Amount}</tr>
   <tr>{item.Charges}</tr>
 </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

这就是表结构。我没有包含任何反应代码。

我引用了此示例代码https://stackblitz.com/edit/js-copy-element?file=index.js。但它没有反应。

使用反应代码如何将表格复制到剪贴板?

小智 9

回答这个问题可能已经太晚了,但这就是我的做法。

我在组件的渲染函数中渲染了元素。

render(){
    return(
        <table id="table">
         .... your table content
        </table>
    )
}
Run Code Online (Sandbox Code Playgroud)

参考上面分享的示例代码简单构建一个复制功能。

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')
Run Code Online (Sandbox Code Playgroud)

}

然后,通过构建这样的元素来调用这个函数

<h1 onClick={()=>{this.copyTable()}}>Copy to table</h1>
Run Code Online (Sandbox Code Playgroud)