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);

点击按钮,获取剪贴板内容如下:

posted @ 2020-01-11 15:17  XYQ全哥  阅读(2034)  评论(0编辑  收藏  举报