首页 > 解决方案 > 按下按钮时如何使用异步功能?

问题描述

我试图在按下按钮时使用异步功能,我需要按下按钮来共享数据。按钮 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);
    }
  }

按下按钮时如何使异步功能起作用?非常感谢

标签: react-native

解决方案


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


推荐阅读