简体   繁体   中英

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.

  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

The screenshot is given below截屏

You can use this package to copy text to the clipboard.

npm i copy-to-clipboard --save

You can create a button or simply copy the text to clipboard as shown inside the 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 ) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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