Pau*_*aul 3 javascript clipboard paste reactjs
我有一个从另一个站点复制的足够长的文本,我必须确保当用户单击按钮时,文本被获取并复制到变量中value。
我尝试使用getData,但它不起作用。
你能帮我个忙吗?
链接:codesandbox
代码:
import React, { useState, useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
export default function MultilineTextFields() {
const [value, setValue] = React.useState("");
const ref = useRef(null);
return (
<Box
component="form"
sx={{
"& .MuiTextField-root": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
>
<Button
variant="contained"
color="primary"
onClick={(e) => {
let paste = (e.clipboardData || window.clipboardData).getData("Text");
setValue(paste);
}}
>
Paste
</Button>
<div>
<TextField
ref={ref}
id="outlined-multiline-static"
label="Multiline"
multiline
rows={40}
value={value}
/>
</div>
</Box>
);
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是,这种方法并不完全跨平台。请参阅此处了解兼容性。
\n您可以使用剪贴板 API,可以这样使用:
\nnavigator.clipboard.readText()\n .then(text => {\n console.log(\'Pasted content: \', text);\n })\n .catch(err => {\n console.error(\'Failed to read clipboard contents: \', err);\n });\nRun Code Online (Sandbox Code Playgroud)\n或者使用异步语法:
\nconst text = await navigator.clipboard.readText();\nRun Code Online (Sandbox Code Playgroud)\n请记住,这将提示用户一个权限请求对话框,因此不可能发生有趣的事情。
\n如果从控制台调用,上面的代码将不起作用。仅当您在活动选项卡中运行代码时它才有效。要从控制台运行代码,您可以设置超时并快速单击网站窗口:
\nsetTimeout(async () => {\n const text = await navigator.clipboard.readText();\n console.log(text);\n}, 2000);\nRun Code Online (Sandbox Code Playgroud)\n在 Google 开发人员文档中阅读有关 API 和用法的更多信息。
\n您也可能可以\xe2\x80\x99t 在代码沙箱上使用它,因为它是一个沙箱环境。
\n| 归档时间: |
|
| 查看次数: |
7672 次 |
| 最近记录: |