React Native - 訪問操作系統剪貼板(Clipboard API的使用)


React Native 為開發者提供了 Clipboard API,讓開發者可以訪問設備操作系統中剪貼板里的內容,或者往剪貼板里存放內容。
 

1、Clipboard API 介紹

Clipboard API 目前還只支持獲取或者存放字符串,它使用比較簡單,只有兩個靜態函數:
  • setString:向剪貼板中存放字符串
  • getString:從剪貼板中取出字符串
 

2、樣例效果圖

(1)點擊“存入剪貼板”按鈕,可以將指定的字符串存入到系統剪貼板中。
(2)點擊“讀取剪貼板”按鈕,可以從系統剪貼板中讀取出數據,並顯示在界面上。
     原文:React Native - 訪問操作系統剪貼板(Clipboard API的使用)       原文:React Native - 訪問操作系統剪貼板(Clipboard API的使用)
 

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

RN學習地址  https://www.hangge.com/blog/cache/category_76_1.html


免責聲明!

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



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