In reactJS, how to copy text to clipboard?

前端 未结 21 1942
刺人心
刺人心 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: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 (
          
    {this.state.copied ? Copied. : null}

    ); } }); ReactDOM.render(, 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.

提交回复
热议问题