简体   繁体   English

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

[英]document.execCommand ('copy') don't work in React

I have the function below that is called on click of a button .我有下面的功能,点击按钮时调用。 Everything works well, but the document.execCommand ('copy') simply does not work.一切正常,但document.execCommand ('copy')根本不起作用。

If I create another button and call only the contents of if in a separate function, it works well.如果我创建另一个按钮并仅在单独的函数中调用if的内容,则效果很好。

I have already tried calling a second function inside the first one, but it also does not work.我已经尝试在第一个函数中调用第二个函数,但它也不起作用。 the copy is only working if it is alone in the function.副本仅在函数中单独存在时才有效。

Does anyone know what's going on?有谁知道发生了什么?

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

You can use lib react-copy-to-clipboard to copy text.您可以使用 lib 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>
    );
}

if you click button Copy button , it will copy the text Text will be copied如果您单击按钮Copy button ,它将复制文本Text will be copied

The lib react-copy-to-clipboard based on copy-to-clipboard does work for me, but if you want to copy the source into your own file, Some places need attention.基于copy-to-clipboard的lib react-copy-to-clipboard确实对我有用,但是如果你想把源码复制到自己的文件中,有些地方需要注意。 The code below works fine.下面的代码工作正常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM