以下是常规的用法:
import?{Clipboard}?from?'react-native';//RN<0.60
import?Clipboard?from?'@react-native-community/clipboard';//RN>0.60
但是我们可以使用react的剪贴板代替以上方式。
例子:
import React, { useState } from 'react'
import { SafeAreaView, View, Text, TouchableOpacity, Clipboard, StyleSheet } from 'react-native'
const App = () => {
const [copiedText, setCopiedText] = useState('')
const copyToClipboard = () => {
Clipboard.setString('hello world')
}
const fetchCopiedText = async () => {
const text = await Clipboard.getString()
setCopiedText(text)
}
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<TouchableOpacity onPress={() => copyToClipboard()}>
<Text>Click here to copy to Clipboard</Text>
</TouchableOpacity>
<TouchableOpacity style={{marginTop:50}} onPress={() => fetchCopiedText()}>
<Text>Click to View copied text</Text>
</TouchableOpacity>
<Text style={styles.copiedText}>{copiedText}</Text>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
copiedText: {
marginTop: 10,
color: 'red'
}
})
export default App
|