react-native - 按下按钮时如何使用异步功能?
问题描述
我试图在按下按钮时使用异步功能,我需要按下按钮来共享数据。按钮 onPress 代码如下所示。
<TouchableOpacity
disabled={buttonDisabled}
onPress={Share}
style={[
styles.btTouchable,
buttonDisabled && styles.buttonDisabled,
]}>
</TouchableOpacity>
我想要分享的功能是这样的:
async function Share() {
try {
let locationData = await new LocationData().getLocationData();
const jsonData = base64.encode(JSON.stringify(locationData));
const title = '';
const filename = '';
const message = '';
const url = 'data:application/json;base64,' + jsonData;
const options = Platform.select({
ios: {
activityItemSources: [
{
placeholderItem: { type: 'url', content: url },
item: {
default: { type: 'url', content: url },
},
subject: {
default: title,
},
linkMetadata: { originalUrl: url, url, title },
},
{
placeholderItem: { type: 'text', content: message },
item: {
default: { type: 'text', content: message },
message: null, // Specify no text to share via Messages app.
},
},
],
},
default: {
title,
subject: title,
url: url,
message: message,
filename: filename,
},
});
Share.open(options)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.message, err.code);
});
} catch (error) {
console.log(error.message);
}
}
按下按钮时如何使异步功能起作用?非常感谢
解决方案
Well, you can try using the function this way:
Share = async () => {
.....
.....
}
and call the function this way:
<TouchableOpacity
disabled={buttonDisabled}
onPress={this.Share}
style={[
styles.btTouchable,
buttonDisabled && styles.buttonDisabled,
]}>
</TouchableOpacity>
[Edit]
To use it with hooks, you can follow this article: React Hooks Basics— Building a React Native App with React Hooks
推荐阅读
- python - Python:如何使用 PyPDF2 解密和 pdfminer 提取文本?
- python - 在使用 microsoft graph api 的某些情况下,电子邮件是无(在获取用户数据时)
- typescript - 只有两个可能值的属性字符串
- javascript - fluent-ffmpeg 没办法加速 GIF
- xpath - Google 表格中的 ImportXML 函数会产生错误“导入的内容为空”!
- php - 注册分类 Wordpress - 自定义列
- angular - 将两个可观察对象组合成角度嵌套的可观察对象?
- html - 使 div 像 svg 一样响应(文本缩小)
- c# - OracleException 不会在 C# 应用程序中被捕获?
- mysql - 指定端口时只能连接到 macOS 上的 Mysql 8