Noob Alert
我试图复制显示在<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有关!
答案 0 :(得分:1)
根据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>