简体   繁体   English

如何在反应中将文本从 UI 复制到剪贴板?

[英]How can one copy text from UI to clipboard in react?

Hi I am trying to copy a text that is outputted from the following code.您好我正在尝试复制从以下代码输出的文本。

<Text style={{color: 'white', textAlign: 'center'}}>
        {rideDuration != '' ? rideDuration + 's' : null}
      </Text>

The setAmountDuration is defined in the following. setAmountDuration 定义如下。

  const calculateAmountDuration = async () => {
    const duration = ride.stop.- ride.start
    let durationSec = duration/1000;
    setrideDuration(durationSec)
  }

I want to copy to clip-board the output 0.08s我想将 output 0.08s 复制到剪贴板

The screenshot is given below截图如下截屏

You can use this package to copy text to the clipboard.您可以使用此 package 将文本复制到剪贴板。

npm i copy-to-clipboard --save

You can create a button or simply copy the text to clipboard as shown inside the function calculateAmountDuration()您可以创建一个按钮或简单地将文本复制到剪贴板,如 function calculateAmountDuration()中所示

 import copy from 'copy-to-clipboard'; function Exmaple { let [rideDuration, setrideDuration] = useState(''); const calculateAmountDuration = async () => { const duration = ride.stop.- ride.start let durationSec = duration/1000; setrideDuration(durationSec); // Copy to Clipboard the moment // the ride duration ios calculated. copy(durationSec.toString()); } // You can also have a button which copies to clipboard const handleCopyToClipboard = (event) => { event.preventDefault(); copy(durationSec.toString()); } return ( <Text style={{color: 'white', textAlign: 'center'}}> {rideDuration?= '': rideDuration + 's' : null} </Text> <button onClick={handleCopyToClipboard}>Copy!</button ) }

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

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