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

document.execCommand ('copy') don't work in 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
        })
}

您可以使用库 react-copy-to-clipboard 来复制文本。

import {CopyToClipboard} from 'react-copy-to-clipboard';`

function(props) {
    return (
       <CopyToClipboard text={'Text will be copied'}>
           <button>Copy button</button>
       </CopyToClipboard>
    );
}

如果您单击按钮 Copy button,它将复制文本 Text will be copied

问题是 copy-to-clipboard 功能将仅作为用户的 click 事件侦听器的直接结果起作用...此事件无法虚拟化并且 execCommand 将无法在其他任何地方起作用分配给事件侦听器的即时回调... 因为 React 虚拟化和抽象化 'events' 那么这很可能就是问题所在,正如建议的那样,您应该使用 React 的 react-copy-to-clipboard.

lib react-copy-to-clipboard based on copy-to-clipboard 对我有用,但是如果你想把源码复制到你自己的文件中,有些地方需要注意。 下面的代码工作正常。

import React, { Component } from 'react'
class App extends Component {
  render() {
    return (
      <div className="App">
        <h1
          onClick={e => {
            const range = document.createRange()
            const selection = document.getSelection()
            const mark = document.createElement('span')
            mark.textContent = 'text to copy'
            // reset user styles for span element
            mark.style.all = 'unset'
            // prevents scrolling to the end of the page
            mark.style.position = 'fixed'
            mark.style.top = 0
            mark.style.clip = 'rect(0, 0, 0, 0)'
            // used to preserve spaces and line breaks
            mark.style.whiteSpace = 'pre'
            // do not inherit user-select (it may be `none`)
            mark.style.webkitUserSelect = 'text'
            mark.style.MozUserSelect = 'text'
            mark.style.msUserSelect = 'text'
            mark.style.userSelect = 'text'
            mark.addEventListener('copy', function(e) {
              e.stopPropagation()
            })

            document.body.appendChild(mark)

            // The following line is very important
            if (selection.rangeCount > 0) {
              selection.removeAllRanges()
            }

            range.selectNodeContents(mark)
            selection.addRange(range)
            document.execCommand('copy')
            document.body.removeChild(mark)
          }}
        >
          Click to Copy Text
        </h1>
      </div>
    )
  }
}

export default App

import React, { Component } from 'react'
class App extends Component {
  render() {
    return (
      <div className="App">
        <h1
          onClick={e => {
            const mark = document.createElement('textarea')
            mark.setAttribute('readonly', 'readonly')
            mark.value = 'copy me'
            mark.style.position = 'fixed'
            mark.style.top = 0
            mark.style.clip = 'rect(0, 0, 0, 0)'
            document.body.appendChild(mark)
            mark.select()
            document.execCommand('copy')
            document.body.removeChild(mark)

          }}
        >
          Click to Copy Text
        </h1>
      </div>
    )
  }
}

export default App