<分区>
菜鸟警报
我试图复制显示的 <this.state.response>
在<h1>
里面. <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 有关!