1. 程式人生 > >React-Native如何複製文字到剪貼簿

React-Native如何複製文字到剪貼簿

React-Native自帶Clipboard API,使用Clipboard可以在iOS和Android的剪貼簿中讀寫內容。

官方API裡面只有複製到剪貼簿和從剪貼簿讀取內容的兩個方法:

static getString()

獲取剪貼簿的文字內容,返回一個Promise語句。

let  str = Clipboard.getString();

static setString(content: string)

設定剪貼簿的文字內容。你可以用下面的方式來呼叫。

function pasteToClipboard(){
    Clipboard.setString('content'
) }

舉個栗子:

import React from 'react'
import PropTypes from 'prop-types'
import {
    View,
    Text,
    TouchableWithoutFeedback,
    Clipboard,
} from 'react-native'

export default class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text:'我是文字'
} } async copy(){ Clipboard.setString(this.state.text); let str = await Clipboard.getString(); console.log(str)//我是文字 } render() { const { text } = this.state; return( <View> <Text>{text}</Text> <TouchableWithoutFeedback onPress={this
.copy.bind(this)}> <View> <Text>點選複製到剪貼簿</Text> </View> </TouchableWithoutFeedback> </View> ) } }

目前暫時只支援複製文字和讀取文字,實際應用中,我們可能希望能夠部分複製,即類似複製從某個位置到某個位置的文字,這個操作如果後續看到的話,我會新增在這後面。