今回はReactNativeのClipboardモジュールを使って、テキストのコピーアンドペーストを制御する基本例を紹介する。
コンテンツ
モジュールのインポート
まず、react-nativeからClipboardモジュールをインポートする。
1 | import { Clipboard } from 'react-native' ; |
setStringメソッドでコピー
テキストをクリップボードへコピーする場合はsetStringメソッドを使う。
1 2 | const text = 'Hello' ; Clipboard.setString(text); |
getStringメソッドでクリップボードの値を取得
逆にクリップボードの値を取得する場合はgetStringメソッドを使う。
1 2 3 4 | async getpb() { const text = await Clipboard.getString(); this .setState({text}) } |
サンプルコード
一つの入力フィールドと、二つのボタンを用意したサンプルコードを書いてみた。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import React, { Component } from 'react' ; import { StyleSheet, View, Button, TextInput, Text, Clipboard } from 'react-native' ; export default class App extends Component { constructor(props) { super (props); this .state = { input: "" , text: "" , }; } pbcopy() { const { input } = this .state; Clipboard.setString(input); } async getpb() { const text = await Clipboard.getString(); this .setState({text}); } render() { return ( <View style={{ flex: 1, justifyContent: "center" , alignItems: "center" , backgroundColor: 'F5FCFF' , }}> <TextInput style={{ width: '100%' , textAlign: "center" , borderBottomWidth: 1, borderColor: '#ccc' , }} value={ this .state.input} onChangeText={input => this .setState({input})} /> <Button onPress={() => { this .pbcopy()}} title= "クリップボードにコピーします" /> <Text>{ this .state.text}</Text> <Button onPress={() => { this .getpb()}} title= "クリップボードのテキストをペーストします" /> </View> ); } } |

Expoでサンプルコードを実行すると、図のようなUIが表示される。
下線を引いた入力フィールドにテキストを入力し、コピーボタンをタップするとクリップボードに入力したテキストがコピーされる。

次にペーストボタンを押してみる。

コピーした「こんにちは」が下の入力フィールドに表示された。