javascript - 如何使用 ReactJS 将内容复制到剪贴板?

标签 javascript reactjs

我想从页面复制特定内容,而不是 HTML 本身。 并且 execCommand 方法已被弃用,我尝试使用 useRef(),但没有进展

如何解决这个问题?

 const div = useRef(null);
 const [copySuccess, setCopySuccess] = useState(false);

 const copyToClipboard = () => {
   const html = div.current.innerHTML.trim();
   navigator.clipboard.writeText(html)
   setCopySuccess(true);
  };


 <div>
        {user.name && (
          <button
            type="submit"
            style={{
              margin-top: '30px',
              margin-bottom: '10px',
              height: '45px',
              width: '85px',
              background-color: '#1d71a5',
              color: '#fff',
              border: 'none',
              border-radius: '5px',
              font-size: '16px',
              cursor: 'pointer',
            }}
            onClick={copyToClipboard}
          >
            Copy
          </button>
        )}
        {copySuccess && (
          <div style={{ color: 'green' }}> ✔︎ Copy with Success! </div>
        )}
      </div>

我要复制签名邮件内容

引用号:https://vdt-email-signature.vercel.app

我尝试使用钩子(Hook)useRef,我尝试使用这个方法:

const copyDivToClipboard = () => {
    const range = document.createRange()
    const selectedDiv = document.getElementById('generated-div')
    range?.selectNode(selectedDiv as Node)
    window?.getSelection()?.removeAllRanges() // clear current selection
    window?.getSelection()?.addRange(range) // to select text
    document.execCommand('copy')
    window?.getSelection()?.removeAllRanges() // to deselect
    alert('Message copied to clipboard!')
}

但是这是一个已弃用的方法。

到目前为止我还没有任何进展。

最佳答案

这种方式可以满足我的要求,但已被弃用

 const div = useRef(null);
 const [copySuccess, setCopySuccess] = useState(false);

  const copyToClipboard = async () => {
    const html = div.current;
    const range = document.createRange();
    if (html) {
      range.selectNode(html);
    }

    const windowSelection = window.getSelection();

    if (windowSelection) {
      windowSelection.removeAllRanges();
      windowSelection.addRange(range);
    }

    try {
      const success = document.execCommand('copy');
      console.log(success ? 'Success' : 'Fail');
      setCopySuccess(true);
    } catch (e) {
      console.log('Fail', e);
    }
    setCopySuccess(true);
  }

关于javascript - 如何使用 ReactJS 将内容复制到剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74660956/

相关文章:

javascript - 在 AngularJS ui-router 中,状态已更改,url 已更改但模板 url 未更改

javascript - 奇怪的 javascript 函数定义语法的文档? () => {}

javascript - 当数据类属性更改时重新渲染 React 组件

javascript - 使用 Rails asset pipeline 与 webpack 来保存 Assets 的优缺点是什么?

javascript - 使用 npm 安装 fork 的 React 组件库

javascript - 在React-router中拦截/处理浏览器的后退按钮?

reactjs - 如果 Context API 不持久,为什么还要使用它?

javascript - 为什么一个数组填充了数据而另一个数组不在控制台 : [ ] and [ {. .} {..} ] 给定相同的数据集?

javascript - 如何在不丢失过渡的情况下进行 DOM 操作?

javascript - 检查窗口可以滚动多远?