【发布时间】:2021-07-07 14:57:42
【问题描述】:
我现在有一个部分有一个表格,我希望用户能够将表格的 HTML 代码复制到剪贴板。
这是我在代码沙箱上的解决方案:live demo
下面的js代码
import React, { useState, useRef } from "react";
export default function App() {
const tableRef = useRef(null);
const [copySuccess, setCopySuccess] = useState("");
const copyToClipboard = (e) => {
const code =tableRef.current.innerHTML;
console.log('code', code);
document.execCommand("copy");
e.target.focus();
setCopySuccess("Copied!");
};
return (
<div className="App">
<div ref={tableRef} className="table">
<table>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
</tbody>
</table>
</div>
{document.queryCommandSupported("copy") && (
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
)}
</div>
);
}
很遗憾,这不是复制 HTML 代码。
我需要更改哪些内容才能将 HTML 复制到剪贴板?
这里有什么问题?
【问题讨论】:
-
需要选择表格的内容。看到这个函数来选择一个表的内容:stackoverflow.com/questions/2044616/…(然后传递它
tableRef.current) -
@PeterCollingridge 检查我的现场演示解决方案单击复制您将看到控制台代码使用 tableRef.current.innerHTML 返回表;问题是如何将其复制到剪贴板
-
您不能使用
document.execCommand("copy"),除非您先选择内容。要从变量写入,您必须使用navigator.clipboard.writeText。详情见:developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/… -
您想将 HTML 文本复制到剪贴板以便用户粘贴 HTML“代码”,还是复制 HTML 元素以便用户粘贴 HTML比如说 Word 或其他应用程序?
-
@KrisztiánBalla 我想复制 HTML 代码,用户可以通过它粘贴到电子邮件中作为签名
标签: javascript reactjs react-hooks use-ref