In reactJS, how to copy text to clipboard?

前端 未结 21 1865
刺人心
刺人心 2020-12-02 04:43

I\'m using ReactJS and when a user clicks a link I want to copy some text to the clipboard.

I am using Chrome 52 and I do not need to support any other browsers.

21条回答
  •  有刺的猬
    2020-12-02 05:11

    You should definitely consider using a package like @Shubham above is advising, but I created a working codepen based on what you described: http://codepen.io/dtschust/pen/WGwdVN?editors=1111 . It works in my browser in chrome, perhaps you can see if there's something I did there that you missed, or if there's some extended complexity in your application that prevents this from working.

    // html
    
      
        
    // js const Hello = React.createClass({ copyToClipboard: () => { var textField = document.createElement('textarea') textField.innerText = 'foo bar baz' document.body.appendChild(textField) textField.select() document.execCommand('copy') textField.remove() }, render: function () { return (

    Click to copy some text

    ) } }) ReactDOM.render( , document.getElementById('container'))

提交回复
热议问题