首先安装:
yarn add clipboard
import React, { useCallback, useEffect, useState } from 'react';
import ClipboardJS from 'clipboard';
import { Link } from 'react-router-dom';
const Home = () => {
const [text, setText] = useState('')
new ClipboardJS('.btn', {
text: function () {
return text
}
})
// 点击按钮请求接口数据
const copyData = useCallback(async () => {
const getData = async () => {
const res = await fetch("http://localhost:8088/experiment_list/detail?exp_group_id=0")
const content = await res.json();
setText(content.name)
}
await getData();
}, [])
// 第一次需要手动触发一次点击按钮事件否则要点击两次才能复制到接口数据
useEffect(() => {
document.querySelector('.btn').click()
}, []);
return (
<div>
<button className="btn" onClick={copyData}>复制</button>
<Link to="/home/child">首页的子页面</Link>
</div>
);
}
export default Home;
点击后就能复制接口的数据了: