React Native 為開發者提供了 Clipboard API,讓開發者可以訪問設備操作系統中剪貼板里的內容,或者往剪貼板里存放內容。
1、Clipboard API 介紹
Clipboard API 目前還只支持獲取或者存放字符串,它使用比較簡單,只有兩個靜態函數:
- setString:向剪貼板中存放字符串
- getString:從剪貼板中取出字符串
2、樣例效果圖
(1)點擊“存入剪貼板”按鈕,可以將指定的字符串存入到系統剪貼板中。
(2)點擊“讀取剪貼板”按鈕,可以從系統剪貼板中讀取出數據,並顯示在界面上。
3、樣例代碼
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TextInput, View, Text, Clipboard } from 'react-native'; export default class Main extends Component { constructor(props) { super(props); this.state = {textFromClipboard:''}; } //從剪貼板中讀取字符串 pasteFromClipboard() { Clipboard.getString().then( (textFromClipboard) => { this.setState({textFromClipboard}); } ).catch( (error) => { console.log("從剪貼板中讀取數據錯誤!"); console.log(error); } ); } //向剪貼板中存入字符串 copyToClipBoard() { Clipboard.setString('歡迎訪問 hangge.com'); } render() { return ( <View style={styles.container}> <View style={styles.flexDirection}> <Text style={styles.buttonStyle} onPress={this.copyToClipBoard.bind(this)}> 存入剪貼板 </Text> <Text style={styles.buttonStyle} onPress={this.pasteFromClipboard.bind(this)}> 讀取剪貼板 </Text> </View> <Text style={styles.info}> {this.state.textFromClipboard} </Text> </View> ); } } const styles = StyleSheet.create({ container:{ flex:1, marginTop:40, alignItems:'center', }, flexDirection:{ flexDirection:'row' }, buttonStyle:{ textAlign:'center', color:'white', margin:10, backgroundColor:'#4CA300', width:140, fontSize:23 }, info:{ fontSize:20, margin:10 }, }); AppRegistry.registerComponent('HelloWorld', () => Main);