首页 > 解决方案 > 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>
  );
}

标签: javascripthtmlreactjsdom

解决方案


使用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>


推荐阅读