Programing

reactJS에서 텍스트를 클립 보드에 복사하는 방법은 무엇입니까?

lottogame 2020. 8. 29. 11:50
반응형

reactJS에서 텍스트를 클립 보드에 복사하는 방법은 무엇입니까?


저는 ReactJS를 사용하고 있으며 사용자가 링크를 클릭하면 일부 텍스트를 클립 보드에 복사하고 싶습니다.

Chrome 52를 사용하고 있으며 다른 브라우저를 지원할 필요가 없습니다.

이 코드로 인해 데이터가 클립 보드에 복사되지 않는 이유를 알 수 없습니다. (코드 스 니펫의 출처는 Reddit 게시물에서 가져온 것입니다).

내가 잘못하고 있니? 누구든지 reactjs를 사용하여 클립 보드에 복사를 구현하는 "올바른"방법이 있다고 제안 할 수 있습니까?

copyToClipboard = (text) => {
  console.log('text', text)
  var textField = document.createElement('textarea')
  textField.innerText = text
  document.body.appendChild(textField)
  textField.select()
  document.execCommand('copy')
  textField.remove()
}

나는 개인적으로 이것을 위해 도서관이 필요하다고 생각하지 않습니다. http://caniuse.com/#feat=clipboard를 살펴보면 현재 꽤 광범위하게 지원되지만 현재 클라이언트에 기능이 있는지 확인하고 그렇지 않은 경우 복사 버튼을 숨기는 등의 작업을 수행 할 수 있습니다.

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 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;

업데이트 : React 16.7.0-alpha.0에서 React Hooks를 사용하여 재 작성

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 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>
  );
}

프로그래밍 방식으로 클립 보드에 데이터를 쓰려면 버튼에이 간단한 인라인 onClick 함수를 사용하십시오.

onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}

위의 @Shubham과 같은 패키지를 사용하는 것이 좋습니다.하지만 설명하신 내용을 기반으로 작동하는 코드 펜을 만들었습니다 : http://codepen.io/dtschust/pen/WGwdVN?editors=1111 . 그것은 크롬의 브라우저에서 작동합니다. 아마도 당신이 놓친 작업이 있는지 또는 응용 프로그램에 이것이 작동하지 못하게하는 확장 된 복잡성이 있는지 확인할 수 있습니다.

// html
<html>
  <body>
    <div id="container">

    </div>
  </body>
</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 (
      <h1 onClick={this.copyToClipboard}>Click to copy some text</h1>
    )
  }
})

ReactDOM.render(
<Hello/>,
  document.getElementById('container'))

가장 간단한 방법은 react-copy-to-clipboardnpm 패키지를 사용하는 것 입니다.

다음 명령으로 설치할 수 있습니다.

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

다음과 같은 방법으로 사용하십시오.

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'));

자세한 설명은 다음 링크에서 제공됩니다.

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

여기에 실행중인 바이올린이 있습니다.


이벤트 클립 보드 데이터 수집 방법 만 사용하지 않는 이유는 무엇 e.clipboardData.setData(type, content)입니까?

제 생각에는 클립 보드 내부에서 smth를 밀어내는 가장 강력한 방법입니다. 이것을 확인하십시오 (기본 복사 작업 중에 데이터를 수정하는 데 사용했습니다).

...

handleCopy = (e) => {
    e.preventDefault();
    e.clipboardData.setData('text/plain', 'Hello, world!');
}

render = () =>
    <Component
        onCopy={this.handleCopy}
    />

나는 그 경로를 따랐다 : https://developer.mozilla.org/en-US/docs/Web/Events/copy

건배!

편집 : 테스트 목적으로 코드 펜을 추가했습니다 : https://codepen.io/dprzygodzki/pen/ZaJMKb


Your code should work perfectly, I use it the same way. Only make sure that if the click event is triggered from within a pop up screen like a bootstrap modal or something, the created element has to be within that modal otherwise it won't copy. You could always give the id of an element within that modal (as a second parameter) and retrieve it with getElementById, then append the newly created element to that one instead of the document. Something like this:

copyToClipboard = (text, elementId) => {
  const textField = document.createElement('textarea');
  textField.innerText = text;
  const parentElement = document.getElementById(elementId);
  parentElement.appendChild(textField);
  textField.select();
  document.execCommand('copy');
  parentElement.removeChild(textField);
}

I've taken a very similar approach as some of the above, but made it a little more concrete, I think. Here, a parent component will pass the url (or whatever text you want) as a prop.

import * as React from 'react'

export const CopyButton = ({ url }: any) => {
  const copyToClipboard = () => {
    const textField = document.createElement('textarea');
    textField.innerText = url;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
  };

  return (
    <button onClick={copyToClipboard}>
      Copy
    </button>
  );
};

For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:

     import React from 'react';
     ....

    //set ref to your div
          setRef = (ref) => {
            // debugger; //eslint-disable-line
            this.dialogRef = ref;
          };

          createMarkeup = content => ({
            __html: content,
          });

    //following function select and copy data to the clipboard from the selected Div. 
   //Please note that it is only tested in chrome but compatibility for other browsers can be easily done

          copyDataToClipboard = () => {
            try {
              const range = document.createRange();
              const selection = window.getSelection();
              range.selectNodeContents(this.dialogRef);
              selection.removeAllRanges();
              selection.addRange(range);
              document.execCommand('copy');
              this.showNotification('Macro copied successfully.', 'info');
              this.props.closeMacroWindow();
            } catch (err) {
              // console.log(err); //eslint-disable-line
              //alert('Macro copy failed.');
            }
          };

              render() {
                    return (
                        <div
                          id="macroDiv"
                          ref={(el) => {
                            this.dialogRef = el;
                          }}
                          // className={classes.paper}
                          dangerouslySetInnerHTML={this.createMarkeup(this.props.content)}
                        />
                    );
            }

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>
        )
    }
}

here is my code:

import React from 'react'

class CopyToClipboard extends React.Component {

  textArea: any

  copyClipBoard = () => {
    this.textArea.select()
    document.execCommand('copy')
  }

  render() {
    return (
      <>
        <input style={{display: 'none'}} value="TEXT TO COPY!!" type="text" ref={(textarea) => this.textArea = textarea}  />
        <div onClick={this.copyClipBoard}>
        CLICK
        </div>
      </>

    )
  }
}

export default CopyToClipboard

참고URL : https://stackoverflow.com/questions/39501289/in-reactjs-how-to-copy-text-to-clipboard

반응형