javascript - copytoclip 板不适用于在反应中隐藏类型的输入文件
问题描述
我正在尝试实现复制到剪贴板功能,如果我将按钮类型传递给文本 ie type="text"
,它工作正常,但在按钮类型时不起作用hidden
。这是 codeSandbox 的链接https://codesandbox.io/s/priceless-blackburn-irwvw?file=/src/App.js
注意:- 不想用 CSS 隐藏输入。请帮助我找到解决方案。提前致谢。
import React, { useRef, useState } from "react";
export default function App() {
const inputRef = useRef(null);
const [copied, setCopy] = useState(false);
const copy = () => {
setCopy(false);
inputRef.current.focus();
inputRef.current.select();
try {
const successful = document.execCommand("copy");
if (successful) {
setCopy({ copied: "Link Copied!" });
}
} catch (err) {
console.log("err=>", err);
setCopy({ copied: err });
}
};
return (
<div className="App">
<button onClick={copy}>Copy </button>
<input
ref={inputRef}
defaultValue={"https:www.google.com"}
type="hidden"
/>
</div>
);
}
解决方案
使用Clipboard.writeText你可以做到。
const { useState, useRef, useEffect } = React;
function App() {
const inputRef = useRef(null);
const [copied, setCopy] = useState(false);
const copy = () => {
setCopy(false);
const value = inputRef.current.value;
navigator.clipboard.writeText(value)
.then(result => {
setCopy({ copied: "Link Copied!" });
})
.catch(err => {
setCopy({ copied: err });
})
};
return (
<div className="App">
<button onClick={copy}>Copy </button>
<input
ref={inputRef}
defaultValue={"https:www.google.com"}
type="hidden"
/>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
推荐阅读
- javascript - 如何从 Firebase 数据库中获取键值为电子邮件的特定数据?
- javascript - 如何调用 modules.export 路由作为 api?
- android - Android NearBy API 非常慢(发现和连接约 10 秒以上)
- svg - SVG 渲染问题。SVG 在不同 Shopify 产品页面上的呈现方式不同
- python - AttributeError:“设置”对象没有属性“MEDIA_URL”
- laravel - 方法 Illuminate\Support\Str::of 不存在
- jquery - ajax 每次都从数据库中获取相同的数据
- pdf-generation - 使用 jasper 软件版本 6.13.0 创建的 pdf 文件中看不到日语内容
- java - Intellij IDEA 不构建 maven 项目
- unity3d - 为什么 Unity 给我构建错误