[React Native]访问操作系统剪贴板 Clipboard
我们之前学习了TextInput组件, 有时候我们需要在TextInput组件中复制或者粘贴一些文字。
React Native为开发者提供了 Clipboard API,Clipboard 组件可以在iOS和Android的剪贴板中读写内容。目前还只支持获取或者存放字符串。
static getString()
获取剪贴板的文本内容,返回一个Promise(后面会介绍)
你可以用下面的方式来调用。
async _getContent() { var content = await Clipboard.getString(); }
static setString(content: string)
设置剪贴板的文本内容。你可以用下面的方式来调用。
_setContent() { Clipboard.setString("hello world"); }
代码比较简单, 直接展示官方例子:
import React, {Component} from "react";
import {
AppRegistry,
StyleSheet,
View,
Text,
Clipboard
} from "react-native";
class AwesomeProject extends Component {
state = {
content: "Content will appear here"
};
//异步函数 箭头函数不需要绑定this了
_setClipboardContent = async () => {
Clipboard.setString("Hello World");
try {
var content = await Clipboard.getString();
this.setState({content});
} catch (e) {
this.setState({content:e.message});
}
};
render() {
return (
<View>
<Text onPress={this._setClipboardContent}
style={{color: "blue",marginTop:100}}>
Tap to put "Hello World" in the clipboard
</Text>
<Text style={{color: "red", marginTop: 20}}>
{this.state.content}
</Text>
</View>
);
}
}
AppRegistry.registerComponent("AwesomeProject", () => AwesomeProject);
运行结果:
更多精彩请关注微信公众账号likeDev
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。