简体   繁体   English

ReactJs 中的复制到剪贴板不适用于弹出窗口/模态

[英]Copy to Clipboard in ReactJs is not working for a popup window/modal

I am trying to copy a text for a button click event present in a popup window and the text is not getting copied.我正在尝试复制弹出窗口 window 中存在的按钮单击事件的文本,并且文本没有被复制。 I tried with this code which works well on a regular window but not for a popup.我尝试使用此代码,该代码在常规 window 上运行良好,但不适用于弹出窗口。 Here is the code:这是代码:

handleClipBoard = () => {           
  var textField = document.createElement('textarea');            
  textField.value = 'text to be copied';         
  document.body.appendChild(textField);         
  textField.select();         
  textField.focus();  // i tried adding focus, It didn't work         
  document.execCommand('copy');             
  textField.remove(textField);          
}        

On reading few posts, I found that document.execCommand('copy') will not work for popup because of focus issues.在阅读了几篇文章后,我发现 document.execCommand('copy') 由于焦点问题而无法用于弹出窗口。 Is there any alternate to this command in ReactJs, or maybe how to get the focus? ReactJs 中是否有此命令的替代方法,或者如何获得焦点?

Thank you.谢谢你。

There's a work-around.有一个解决方法。

Instead of appending the new input to the body element, you can append it to your modal's element, or some other container inside that modal.无需将新输入附加到body元素,您可以将其 append 到您的模态元素或该模态内的其他容器。

So it should work with something like this:所以它应该使用这样的东西:

const copyToClipboard = (textToCopy, containerElement = document.body) => {           
  const textField = document.createElement('textarea');            
  textField.value = textToCopy;
  containerElement.appendChild(textField);      
  textField.select();         
  document.execCommand('copy');             
  containerElement.removeChild(textField);          
}        

If you're using something like react-bootstrap with enforceFocus functionality, you're adding the element outside of the Modal and the focus is forced upon the modal.如果您使用带有 enforceFocus 功能react-bootstrap之类的东西,则您将在模态之外添加元素,并且焦点被强制在模态上。

If you don't need this functionality, you can add enforceFocus={false} to your modal construction.如果您不需要此功能,您可以将enforceFocus={false}添加到您的模态结构中。 This allows you to target elements outside the modal and do things, like in this case, copy them.这使您可以定位模式之外的元素并执行操作,例如在本例中,复制它们。

Example:例子:

<Modal show={props.show} onHide={props.close} dialogClassName="modal-lg"
    style={MODAL_STYLES} enforceFocus={false}>
  <Modal.Header closeButton>Example</Modal.Header>
  <Modal.Body>
    copyToClipboard("test");
  </Modal.Body>
</Modal>

Without enforceFocus set to false , I wouldn't be able to copy the "test" string.如果没有enforceFocus设置为false ,我将无法复制“test”字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM