javascript - document.execCommand ('copy' ) 在 React 中不起作用

标签 javascript reactjs execcommand

我有下面的函数,它是在点击按钮时调用的。一切正常,但 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/

相关文章:

javascript - 在react-native中动态创建json

javascript - HTML 富文本编辑器与 justify* 命令相关的问题

javascript - JQuery MultiSelect 更新实体数据源

javascript - 类型 'csrf_token' 上不存在属性 'Object'

javascript - React 中的 HTML5 音频标签

javascript - ReactJS 是否重用导入的包?

javascript:如何反转 range.execCommand 方法

javascript - 有比 document.execCommand 更好的东西吗?

javascript - 脚本 5009 : 'fetch' is undefined

javascript - 如何更改 Bootstrap 弹出窗口箭头的大小