[英]How can I copy text to clipboard with ReactJS?
我正在构建一个将文本转换为数组的 React web 应用程序。 我希望用户单击最终的 output 并能够将其复制到剪贴板上。
我正在关注许多网站和教程。 我是 ReactJS 的新手,我不知道我的代码有什么问题!
这是 function 我
copyToClipboard() {
const {array} = this.state
const textToCopy = "const myArray =" + JSON.stringify(array)
textToCopy.select()
document.execCommand("copy")
this.setState({copySuccess: true})
}
通过此按钮调用 function。 该按钮工作正常:
<button onClick={this.copyToClipboard.bind(this)} id="copy-to-clipboard" className="btn btn-normal">Copy to clipboard</button>
我觉得问题出在下面function这部分,不知道怎么解决!
textToCopy.select()
document.execCommand("copy")
链接到整个应用程序+代码:
const copyToClipboard = (content: any) => {
const el = document.createElement('textarea');
el.value = content;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
这是我的解决方案,它包含 3 个步骤:
您应该使用从中复制的 DOM 元素。 这是一个文本区域的例子。 您不能在字符串值上调用 select。
正如@Rosen 提到的,您应该在 DOM 元素上使用副本
像这样的东西
<textarea
ref={(textarea) => this.textArea = textarea}
value='Some text to copy'
/>
然后在你的 function 中调用它
copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
};
export const CopyTextIcon: React.FC = () => {
function copyToClipboard() {
const tempInput = document.createElement('input')
tempInput.value = 'text'
document.body.appendChild(tempInput)
tempInput.select()
document.execCommand('copy')
document.body.removeChild(tempInput)
}
return (
<div onClick={()=>copyToClipboard('topRight')}>
<img src="/images/ic-SHARE.svg" alt="share" />
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.