javascript - document.execCommand ('copy') 在 React 中不起作用
问题描述
我有下面的功能,点击按钮即可调用。一切正常,但document.execCommand ('copy')
根本不起作用。
如果我创建另一个按钮并仅调用if
单独函数中的内容,则效果很好。
我已经尝试在第一个函数中调用第二个函数,但它也不起作用。副本只有在函数中单独使用时才有效。
有谁知道发生了什么?
copyNshort = () => {
const bitly = new BitlyClient('...') // Generic Access Token bit.ly
let txt = document.getElementById('link-result')
bitly.shorten(txt.value)
.then((res) => {
this.setState({ shortedLink: res.url })
if (this.state.shortedLink !== undefined) {
document.getElementById('link-result-shorted').select() // get textarea value and select
document.execCommand('copy') // copy selected
console.log('The link has been shortened and copied to clipboard!')
ReactDOM.render(<i className="fas fa-clipboard-check"></i>, document.getElementById('copied'))
}
console.log('Shortened link ', res.url) // Shorted url
})
}
解决方案
问题是该copy-to-clipboard
功能只能作为用户click
事件监听器的直接结果工作......这个事件不能被虚拟化,并且 execCommand 除了分配给事件监听器的立即回调之外将无法工作......因为反应虚拟化和抽象“事件”,那么这很可能是问题所在,并且建议您应该使用 React 的react-copy-to-clipboard
.
推荐阅读
- r - 我需要按分类值(邻域)排序的捐赠信息的描述性统计数据(平均值,超过一定数量的百分比)
- javascript - 如何使用 ajax 提交带有文件上传的表单
- gallery - 如何更新旧的 Blue Imp Gallery 脚本并使其再次运行?
- xcode - Xcode 中的“无法加载作者信息”
- python-3.x - vmware截图时win32部分被黑屏
- xcode - Flutter:如果我从 xcode 运行应用程序,则存在差异
- javascript - 从解析的 json 到输入值的日期对象
- python - 使用 specutils 与 Python 进行连续拟合
- c# - 转换未知的 IEnumerable
到列表 - java - 如何配置非持久性 Ignite 以防止交换?