前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【译】React Native URL 路由库

【译】React Native URL 路由库

作者头像
腾讯IVWEB团队
发布2020-06-28 00:07:25
1.2K0
发布2020-06-28 00:07:25
举报
文章被收录于专栏:腾讯IVWEB团队的专栏

react-native-deep-linking

一个 React Native 路由匹配用于处理 deep links 的库

安装

这个包已经发布到 npm 上面去了:

代码语言:javascript
复制
npm install react-native-deep-linking
在你的项目中添加 deep link 支持

对于 iOS

  1. 确保你已经在你 app 中的 Info.plist 文件中注册了 URL Schemes 项目
  2. 把下面的代码加到你的 AppDelegate.m 文件中
代码语言:javascript
复制
#import "RCTLinkingManager.h"

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

// Only if your app is using [Universal Links](https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/AppSearch/UniversalLinks.html).
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
 return [RCTLinkingManager application:application
                  continueUserActivity:userActivity
                    restorationHandler:restorationHandler];
}

对于 Android

可以参考链接:https://developer.android.com/training/app-indexing/deep-linking.html

更多相关的信息可以参考:https://facebook.github.io/react-native/docs/linking.html

用法

  1. 引入 DeepLinking
代码语言:javascript
复制
import DeepLinking from 'react-native-deep-linking';
  1. 注册 schemes
代码语言:javascript
复制
DeepLinking.addScheme('example://');
  1. 新增事件监听
代码语言:javascript
复制
import { Linking } from 'react-native';

Linking.addEventListener('url', handleUrl);

const handleUrl = ({ url }) => {
  Linking.canOpenURL(url).then((supported) => {
    if (supported) {
      DeepLinking.evaluateUrl(url);
    }
  });
};
  1. 注册路由
代码语言:javascript
复制
DeepLinking.addRoute('/test/:id', (response) => {
  // example://test/23
  console.log(response.id); // 23
});
  1. 打开外部 urlexternal url(Optional)) 如果你的 app 是从一个已经在 app 中注册了的外部 url 启动,你可以在任意你用到的组件中访问或者调用
代码语言:javascript
复制
componentDidMount() {
  var url = Linking.getInitialURL().then((url) => {
    if (url) {
      Linking.openURL(url);
    }
  }).catch(err => console.error('An error occurred', err));
}

举个栗子

代码语言:javascript
复制
import React, { Component } from 'react';
import { Button, Linking, StyleSheet, Text, View } from 'react-native';

import DeepLinking from 'react-native-deep-linking';

export default class App extends Component {
  state = {
    response: {},
  };

  componentDidMount() {
    DeepLinking.addScheme('example://');
    Linking.addEventListener('url', this.handleUrl);

    DeepLinking.addRoute('/test', (response) => {
      // example://test
      this.setState({ response });
    });

    DeepLinking.addRoute('/test/:id', (response) => {
      // example://test/23
      this.setState({ response });
    });

    DeepLinking.addRoute('/test/:id/details', (response) => {
      // example://test/100/details
      this.setState({ response });
    });

    Linking.getInitialURL().then((url) => {
      if (url) {
        Linking.openURL(url);
      }
    }).catch(err => console.error('An error occurred', err));
  }

  componentWillUnmount() {
    Linking.removeEventListener('url', this.handleUrl);
  }

  handleUrl = ({ url }) => {
    Linking.canOpenURL(url).then((supported) => {
      if (supported) {
        DeepLinking.evaluateUrl(url);
      }
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.container}>
          <Button
            onPress={() => Linking.openURL('example://test')}
            title="Open example://test"
          />
          <Button
            onPress={() => Linking.openURL('example://test/23')}
            title="Open example://test/23"
          />
          <Button
            onPress={() => Linking.openURL('example://test/100/details')}
            title="Open example://test/100/details"
          />
        </View>
        <View style={styles.container}>
          <Text style={styles.text}>{this.state.response.scheme ? `Url scheme: ${this.state.response.scheme}` : ''}</Text>
          <Text style={styles.text}>{this.state.response.path ? `Url path: ${this.state.response.path}` : ''}</Text>
          <Text style={styles.text}>{this.state.response.id ? `Url id: ${this.state.response.id}` : ''}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    margin: 10,
  },
});

Routes

正常的 deep link URL 的格式如下:<scheme>://<host>/<path-component>

举个栗子:facebook://profile

代码语言:javascript
复制
// The following route matches the URL.
DeepLinking.addRoute('/profile', ({ scheme, path }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile`
});

// The following route does NOT match the URL.
DeepLinking.addRoute('profile', () => { ... });

接着举个栗子:facebook://profile/33138223345

代码语言:javascript
复制
// The following route matches the URL.
DeepLinking.addRoute('/profile/:id', ({ scheme, path, id }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/33138223345`
  console.log(id);     // `33138223345`
});

再举个栗子:facebook://profile/12/posts/403

代码语言:javascript
复制
// The following route matches the URL.
DeepLinking.addRoute('profile/:id/posts/:postId', ({ scheme, path, id, postId }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/12/posts/403`
  console.log(id);     // `12`
  console.log(postId); // `403`
});

正则匹配路由

需要一些功能更加强大的路由?你可以在路由中增加自己的正则表达式~

举个栗子:facebook://profile/123/details

代码语言:javascript
复制
const regex = /\/profile\/(.*)\/details/g;
DeepLinking.addRoute(regex, ({ scheme, path, match }) => {
  console.log(scheme); // `facebook://`
  console.log(path);   // `/profile/33138223345/details`
  console.log(match);  // `[ "/profile/123/details", "123" ]`
});

GitHub

react-native-deep-linking

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • react-native-deep-linking
  • 安装
    • 在你的项目中添加 deep link 支持
    • 用法
    • 举个栗子
    • Routes
      • 正则匹配路由
      • GitHub
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档