如何在 React JS 中复制到剪贴板

How to Copy to clipboard in React JS

菜鸟警报

我试图复制 <h1> 中显示的 <this.state.response><p> 标签应该充当复制按钮,我想为其提供复制操作。我尝试使用 react-copy-to-clipboard 包但失败了,因为我的代码中已经定义了一些状态。

<div>
    //content to be copied
            <h1 id="copy" className="password-display"> {this.state.response}</h1>
     //acts as the copy button
            <p className="copy-clipboard">Copy to clipboard</p>
</div>

Home.js

import React, { Component } from "react";
import { Container, Row, Col, ButtonGroup, Button } from "reactstrap";
import {CopyToClipboard} from 'react-copy-to-clipboard';
import Header from "./Header.js";
import Footer from "./Footer.js";

import "./Home.css";


export default class Home extends Component {
  state = {

    response: ''
  };


  componentDidMount() {
    this.callApi()
      .then(res => this.setState({ response: res.chunk }))
      .catch(err => console.log(err));
  }



  callApi = async () => {
    const response = await fetch('/password-api');
    const body = await response.json();

    if (response.status !== 200) throw Error(body.message);

    return body;
  };

  handleClick = async () => {
    await this.callApi()
       .then(res => this.setState({ response: res.chunk }))
 };

  
  render() {
    return (
      <div className="App-header">
        <Header />

        <Container>
          <Row>
            <Col sm="12" md={{ size: 8, offset: 2 }}>
          <div>
                <h1 id="copy" className="password-display"> {this.state.response}</h1>
                <p className="copy-clipboard">Copy to clipboard</p>
              </div>
            
       
               
              {/* <ButtonGroup>
            <Button>Secure</Button>
            <Button>Complex</Button>
              </ButtonGroup> */}
            </Col>
          </Row>
          <Row>
            <Col sm="12" md={{ size: 8, offset: 2 }}>
              <button onClick={this.handleClick} id="get-pass-button" className="button">
                Generate Password
              </button>
            </Col>
          </Row>
        </Container>
        <Footer />
      </div>
    );
  }
}

我认为这个问题与 npm react-copy-to-clipboard 有关!

根据 react-copy-to-clipboard 的文档,您只需包装充当按钮的元素即可进行复制。所以在你的 render() 函数中:

<div>
    <h1 id="copy" className="password-display"> {this.state.response}</h1>
    <CopyToClipboard text={this.state.response}>
        <p className="copy-clipboard">Copy to clipboard</p>
    </CopyToClipboard>
</div>