找到了最好的方法。我的意思是最快的方法:w3school
https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
在React功能组件内部。创建一个名为handleCopy的函数:
function handleCopy() {
// get the input Element ID. Save the reference into copyText
var copyText = document.getElementById("mail")
// select() will select all data from this input field filled
copyText.select()
copyText.setSelectionRange(0, 99999)
// execCommand() works just fine except IE 8. as w3schools mention
document.execCommand("copy")
// alert the copied value from text input
alert(`Email copied: ${copyText.value} `)
}
<>
<input
readOnly
type="text"
value="exemple@email.com"
id="mail"
/>
<button onClick={handleCopy}>Copy email</button>
</>
如果不使用React,w3schools也提供了一种很酷的方法,包括以下工具提示:https : //www.w3schools.com/howto/tryit.asp? filename =tryhow_js_copy_clipboard2
如果使用React,那么可以考虑:使用Toastify来警告消息。
https://github.com/fkhadra/react-toastify这是非常易于使用的库。安装后,您可以更改此行:
alert(`Email copied: ${copyText.value} `)
对于类似:
toast.success(`Email Copied: ${copyText.value} `)
如果要使用它,请不要忘记安装toastify。导入ToastContainer并同时敬酒CSS:
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
并在return内部添加吐司容器。
import React from "react"
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
export default function Exemple() {
function handleCopy() {
var copyText = document.getElementById("mail")
copyText.select()
copyText.setSelectionRange(0, 99999)
document.execCommand("copy")
toast.success(`Hi! Now you can: ctrl+v: ${copyText.value} `)
}
return (
<>
<ToastContainer />
<Container>
<span>E-mail</span>
<input
readOnly
type="text"
value="myemail@exemple.com"
id="mail"
/>
<button onClick={handleCopy}>Copy Email</button>
</Container>
</>
)
}