我想从页面复制特定内容,而不是 HTML 本身。 并且 execCommand 方法已被弃用,我尝试使用 useRef(),但没有进展
如何解决这个问题?
const div = useRef(null);
const [copySuccess, setCopySuccess] = useState(false);
const copyToClipboard = () => {
const html = div.current.innerHTML.trim();
navigator.clipboard.writeText(html)
setCopySuccess(true);
};
<div>
{user.name && (
<button
type="submit"
style={{
margin-top: '30px',
margin-bottom: '10px',
height: '45px',
width: '85px',
background-color: '#1d71a5',
color: '#fff',
border: 'none',
border-radius: '5px',
font-size: '16px',
cursor: 'pointer',
}}
onClick={copyToClipboard}
>
Copy
</button>
)}
{copySuccess && (
<div style={{ color: 'green' }}> ✔︎ Copy with Success! </div>
)}
</div>
我要复制签名邮件内容
引用号:https://vdt-email-signature.vercel.app
我尝试使用钩子(Hook)useRef,我尝试使用这个方法:
const copyDivToClipboard = () => {
const range = document.createRange()
const selectedDiv = document.getElementById('generated-div')
range?.selectNode(selectedDiv as Node)
window?.getSelection()?.removeAllRanges() // clear current selection
window?.getSelection()?.addRange(range) // to select text
document.execCommand('copy')
window?.getSelection()?.removeAllRanges() // to deselect
alert('Message copied to clipboard!')
}
但是这是一个已弃用的方法。
到目前为止我还没有任何进展。
最佳答案
这种方式可以满足我的要求,但已被弃用
const div = useRef(null);
const [copySuccess, setCopySuccess] = useState(false);
const copyToClipboard = async () => {
const html = div.current;
const range = document.createRange();
if (html) {
range.selectNode(html);
}
const windowSelection = window.getSelection();
if (windowSelection) {
windowSelection.removeAllRanges();
windowSelection.addRange(range);
}
try {
const success = document.execCommand('copy');
console.log(success ? 'Success' : 'Fail');
setCopySuccess(true);
} catch (e) {
console.log('Fail', e);
}
setCopySuccess(true);
}
关于javascript - 如何使用 ReactJS 将内容复制到剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74660956/