我有下面的函数,它是在点击按钮时调用的。一切正常,但 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 的 react-copy-to-clipboard
。
关于javascript - document.execCommand ('copy' ) 在 React 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51129888/