ReactNative: 剪貼板Clipboard的使用


一、介紹

“剪貼板Clipboard”為用戶提供了一個界面,可在iOS和Android上從訪問系統的剪貼板設置和獲取內容。

 

二、API

Clipboard提供的API相當簡單,只有兩個方法,一個是設置內容到剪貼板,另一個則是從剪貼板獲取設置的內容。如下所示:

//設置內容到剪貼板
setString(content: string) {
    Clipboard.setString(content);
}

//獲取剪貼板上的內容,返回的是一個Promise異步函數
getString(): Promise<string> {
    return Clipboard.getString();
}

 

三、使用

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';

import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    TouchableHighlight,
    Clipboard
} from 'react-native';

export default class ReactNativeDemo extends Component {

    //異步處理
    _handleClipboardContent = async () => {

        //設置內容到剪貼板
        Clipboard.setString("Welcome to you!");

        //從剪貼板獲取內容
        Clipboard.getString().then( (content)=>{
            alert('content: '+content)
        }, (error)=>{
            console.log('error:'+error);
        })
    };

    render() {
        return (
            <View style={[styles.flex,styles.bgColor,styles.center]}>
                <TouchableHighlight onPress={this._handleClipboardContent}>
                    <Text style={{color:'red',fontSize:30}}>Click</Text>
                </TouchableHighlight>
            </View>
        );
    }
}



const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    bgColor: {
      backgroundColor: 'white'
    },
    center: {
        alignItems: 'center',
        justifyContent: 'center',
    }
});

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

點擊按鈕,獲取剪貼板內容如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM