In reactJS, how to copy text to clipboard?

前端 未结 21 1866
刺人心
刺人心 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 04:59

    use this command to pass your value to the function

    var promise = navigator.clipboard.writeText(newClipText)
    
    0 讨论(0)
  • 2020-12-02 05:01

    If you want to select from the DIV instead of the text field, here is the code. The "code" is the value that has to be copied

    import React from 'react'
    class CopyToClipboard extends React.Component {
    
      copyToClipboard(code) {
        var textField = document.createElement('textarea')
        textField.innerText = code
        document.body.appendChild(textField)
        textField.select()
        document.execCommand('copy')
        textField.remove()
      }
      render() {
        return (
          <div onClick={this.copyToClipboard.bind(this, code)}>
            {code}
          </div>
    
        )
      }
    }
    
    export default CopyToClipboard
    
    0 讨论(0)
  • 2020-12-02 05:03

    You can also use react hooks into function components or stateless components with this piece of code: PS: Make sure you install useClippy through npm/yarn with this command: npm install use-clippy or yarn add use-clippy

    import React from 'react';
    import useClippy from 'use-clippy';
    
    export default function YourComponent() {
    
    // clipboard is the contents of the user's clipboard.
      // setClipboard('new value') wil set the contents of the user's clipboard.
    
      const [clipboard, setClipboard] = useClippy();
    
      return (
        <div>
    
          {/* Button that demonstrates reading the clipboard. */}
          <button
            onClick={() => {
              alert(`Your clipboard contains: ${clipboard}`);
            }}
          >
            Read my clipboard
          </button>
    
          {/* Button that demonstrates writing to the clipboard. */}
          <button
            onClick={() => {
              setClipboard(`Random number: ${Math.random()}`);
            }}
          >
            Copy something
          </button>
        </div>
      );
    }
    
    0 讨论(0)
  • 2020-12-02 05:04
    import React, { Component } from 'react';
    
    export default class CopyTextOnClick extends Component {
        copyText = () => {
            this.refs.input.select();
    
            document.execCommand('copy');
    
            return false;
        }
    
        render () {
            const { text } = this.state;
    
            return (
                <button onClick={ this.copyText }>
                    { text }
    
                    <input
                        ref="input"
                        type="text"
                        defaultValue={ text }
                        style={{ position: 'fixed', top: '-1000px' }} />
                </button>
            )
        }
    }
    
    0 讨论(0)
  • 2020-12-02 05:05

    I personally don't see the need for a library for this. Looking at http://caniuse.com/#feat=clipboard it's pretty widely supported now, however you can still do things like checking to see if the functionality exists in the current client and simply hide the copy button if it doesn't.

    import React from 'react';
    
    class CopyExample extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = { copySuccess: '' }
      }
    
      copyToClipboard = (e) => {
        this.textArea.select();
        document.execCommand('copy');
        // This is just personal preference.
        // I prefer to not show the whole text area selected.
        e.target.focus();
        this.setState({ copySuccess: 'Copied!' });
      };
    
      render() {
        return (
          <div>
            {
             /* Logical shortcut for only displaying the 
                button if the copy command exists */
             document.queryCommandSupported('copy') &&
              <div>
                <button onClick={this.copyToClipboard}>Copy</button> 
                {this.state.copySuccess}
              </div>
            }
            <form>
              <textarea
                ref={(textarea) => this.textArea = textarea}
                value='Some text to copy'
              />
            </form>
          </div>
        );
      }
    
    }
        
    export default CopyExample;
    

    Update: Rewritten using React Hooks in React 16.7.0-alpha.0

    import React, { useRef, useState } from 'react';
    
    export default function CopyExample() {
    
      const [copySuccess, setCopySuccess] = useState('');
      const textAreaRef = useRef(null);
    
      function copyToClipboard(e) {
        textAreaRef.current.select();
        document.execCommand('copy');
        // This is just personal preference.
        // I prefer to not show the whole text area selected.
        e.target.focus();
        setCopySuccess('Copied!');
      };
    
      return (
        <div>
          {
           /* Logical shortcut for only displaying the 
              button if the copy command exists */
           document.queryCommandSupported('copy') &&
            <div>
              <button onClick={copyToClipboard}>Copy</button> 
              {copySuccess}
            </div>
          }
          <form>
            <textarea
              ref={textAreaRef}
              value='Some text to copy'
            />
          </form>
        </div>
      );
    }
    
    0 讨论(0)
  • 2020-12-02 05:09

    The simplest way will be use the react-copy-to-clipboard npm package.

    You can install it with the following command

    npm install --save react react-copy-to-clipboard
    

    Use it in the following manner.

    const App = React.createClass({
      getInitialState() {
        return {value: '', copied: false};
      },
    
    
      onChange({target: {value}}) {
        this.setState({value, copied: false});
      },
    
    
      onCopy() {
        this.setState({copied: true});
      },
    
    
      render() {
        return (
          <div>
    
              <input value={this.state.value} size={10} onChange={this.onChange} />
    
            <CopyToClipboard text={this.state.value} onCopy={this.onCopy}>
              <button>Copy</button>
            </CopyToClipboard>
    
                    <div>
            {this.state.copied ? <span >Copied.</span> : null}
                    </div>
            <br />
    
            <input type="text" />
    
          </div>
        );
      }
    });
    
    ReactDOM.render(<App />, document.getElementById('container'));
    

    A detailed explanation is provided at the following link

    https://www.npmjs.com/package/react-copy-to-clipboard

    Here is a running fiddle.

    0 讨论(0)
提交回复
热议问题