简体   繁体   English

React—复制到剪贴板—按钮

[英]React— Copy to clipboard— Button

I have something like this in a div我在 div 中有这样的东西

  <div className="generated-voucher-code-details">
                <p>Your voucher Code is <span style={{color:'#000000', fontWeight:'500'}}>“X1X1X1“</span>.</p>
                <p>To know more on how to redeem the gift card visit the link <span style={{color:'#C7417B'}}>stores.com</span></p>
                <p>Choose Preferred date, Time, Number of People and Book Now.</p>
                <p>Apply voucher code in Have a Xoxo Voucher Check Box.</p>
                <p>Pay Extra Amount if any through other mode of payments.</p>
                <p>Your order is successfully placed.</p>
                <p>You will receive confirmation within 24 hours.</p>
  </div>

This Div is in a box assume, below this box, I have a button.这个 Div 在一个盒子里,假设在这个盒子下面,我有一个按钮。

Now, How to copy the whole text when we click on this button?现在,当我们点击这个按钮时,如何复制整个文本?

welcome to stack overflow.欢迎堆栈溢出。

Please check below a working code sample.请检查下面的工作代码示例。

import React, { useRef } from 'react';

export default function () {
   const divRef = useRef();
   const copyToCB = () => {
    const div = document.createRange();

    div.setStartBefore(divRef.current);
    div.setEndAfter(divRef.current);
    window.getSelection().empty();
    window.getSelection().addRange(div);
    document.execCommand('copy')
}
return (
    <>
        <div className="generated-voucher-code-details" ref={divRef}>
            <p>Your voucher Code is <span style={{ color: '#000000', fontWeight: '500' }}>“X1X1X1“</span>.</p>
            <p>To know more on how to redeem the gift card visit the link <span style={{ color: '#C7417B' }}>stores.com</span></p>
            <p>Choose Preferred date, Time, Number of People and Book Now.</p>
            <p>Apply voucher code in Have a Xoxo Voucher Check Box.</p>
            <p>Pay Extra Amount if any through other mode of payments.</p>
            <p>Your order is successfully placed.</p>
            <p>You will receive confirmation within 24 hours.</p>
        </div>
        <button onClick={copyToCB}>Copy to CB</button>
    </>
)
}

Thanks to https://www.sitepoint.com/community/t/how-to-select-text-between-div-tag-using-js/4283/5感谢https://www.sitepoint.com/community/t/how-to-select-text-between-div-tag-using-js/4283/5

You can use document.execCommand("copy") to implement it.您可以使用document.execCommand("copy")来实现它。

For more details head to this link .有关更多详细信息,请访问此链接

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

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