- React Native Cookbook
- Dan Ward
- 279字
- 2025-04-04 14:57:29
How it works...
In step 2, we defined all the links that our app uses. Each link object has a type property that we use in the handleButtonPress method defined in step 5.
This handleButtonPress function uses the link's type to determine which one of two strategies will be used. If the link's type is 'internal link', we want to open the link with the device browser as a modal that pops up within the app itself. For this purpose, we can use Expo's WebBrowser helper, passing the URL to its openBrowserAsync method. If the link's type is 'external link', we'll open the link with React Native's Linking helper. This lets you see the different ways you can open a website from your app.
The Linking helper can handle protocols other than HTTP and HTTPS as well. By simply using the proper protocol in the link we pass to Linking.openURL, we can open the telephone (tel:), messaging (sms:), or email (mailto:).
Linking.openURL can also handle deep links to other applications, as long as the app you want to link to has a protocol for doing so, such as how we open Slack by using the slack:// protocol. For more information on Slack's deep linking protocol and what you can do with it, visit their documentation at https://api.slack.com/docs/deep-linking.
In step 5, we catch any error caused by calling Linking.openURL, check whether the error was caused by the Slack protocol using message.includes('slack://'), and if so, we know the Slack app is not installed on the device. In this case, we fire handleMissingApp, which opens the app store link for Slack using the appropriate link, as determined by Platform.OS.