首页 > 解决方案 > 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
        })
}

标签: javascriptreactjsexeccommand

解决方案


问题是该copy-to-clipboard功能只能作为用户click事件监听器的直接结果工作......这个事件不能被虚拟化,并且 execCommand 除了分配给事件监听器的立即回调之外将无法工作......因为反应虚拟化和抽象“事件”,那么这很可能是问题所在,并且建议您应该使用 React 的react-copy-to-clipboard.


推荐阅读