反应:将组件状态值复制到剪贴板,而没有虚拟元素 [英] react: copy component state value to clipboard without dummy element

查看:67
本文介绍了反应:将组件状态值复制到剪贴板,而没有虚拟元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,有一个用例:用户单击一个按钮,然后将一些数据复制到剪贴板以进行下一步.

In my project there is one usage case: user click one button and then copy some data to clipboard for next step.

复制的数据与单击的按钮有关,并以组件状态存储.

The copied data is related to the clicked button, and is stored in the component state.

我进行了一些搜索,然后找到了可能的解决方案,如下所示:

I do some search, and find the potential solution as following:

function copyToClipboard(text){
    var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    dummy.setAttribute('value', text);
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

在某种程度上,我们需要创建一个虚拟元素,将复制的数据设置为虚拟元素并选择该元素,然后执行 execCommand(copy)方法.

to some extend, we need to create a dummy element, set the copied data to the dummy element and select the element, then execute the execCommand(copy) method.

是否可以在不创建虚拟元素的情况下执行此操作?我知道有一些关于剪贴板的react插件,但是我只想使用香草javascript.谢谢

is it possible to do this without creating dummy element? I know there are some react plugin about clipboard, but I just want to use vanilla javascript. thank you

推荐答案

您的解决方案效果很好.

Your solution works well.

如果要复制的值尚未在DOM上呈现,则您的 Document.createElement('input')... 方法是创建> Document 知道,但是用户看不到.一旦使用 .createElement(),您就可以调用

If the value you want to copy is not yet rendered on the DOM, your Document.createElement('input')... method is a good way to create a document node that Document knows about, but that is not visible to the user. Once you use .createElement() you can then call execCommand() on it to copy the value to the clipboard.

execCommand()方法由HTML5的 Document 公开.这意味着 Document 必须先了解您要定位的节点,然后才能使用该方法(这称为选择).

The execCommand() method is exposed by HTML5's Document. This means Document has to know about the node you are targeting before you can use the method (this is called Selection).

但是,如果您想从已经在dom上渲染的元素中复制文本(例如,表单中的输入),则可以使用React的这是一个使用 ref 进行此操作的好例子.这非常简单,因此使用可能会过大.

However, if you want to copy text from an element already rendered on the dom (e.g an input in a form), you could use React's callback ref. Here's a good example of using ref to do this. It's pretty simple, so using a library is likely to be overkill.

这篇关于反应:将组件状态值复制到剪贴板,而没有虚拟元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆