【发布时间】:2021-12-06 11:23:57
【问题描述】:
我有一个部分,我希望用户将 html 复制到剪贴板,这个元素应该隐藏在这里是我目前所拥有的
现场演示:live demo
这是我到目前为止的代码。
export default function App() {
const tableRef = useRef(null);
const textRef = useRef(null);
const [copySuccess, setCopySuccess] = useState("");
const copyToClipboard = (e) => {
let tableRange = document.createRange();
tableRange.selectNodeContents(tableRef.current);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(tableRange);
document.execCommand("Copy");
sel.removeAllRanges();
setCopySuccess("Copied!");
};
return (
<div className="App">
<textarea
ref={textRef}
style={{ opacity: 0, position: "absolute", top: "-200px" }}
></textarea>
<div
aria-hidden="true"
ref={tableRef}
className="table"
style={{ display: "none" }}
>
<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 表格复制到剪贴板
我需要做什么才能将该隐藏元素复制到剪贴板?
【问题讨论】:
-
好的,你要复制哪一部分?
textarea?div?table? -
@hisam 桌子
标签: javascript reactjs html-table react-hooks use-ref