美文网首页
React Native通过Linking接收并处理App Li

React Native通过Linking接收并处理App Li

作者: _敏讷 | 来源:发表于2019-12-24 23:40 被阅读0次

    当React Native的项目从外部链接启动时, 有一个较为方便的方法来处理该链接用于获取变量或跳转到相应的页面: Linking.getInitialURL

    import { Linking } from 'react-native';
    import URL from 'url';
    componentDidMount() {
      Linking.getInitialURL().then(url) => {
        if (url) {
          const { protocol, host, pathname, search, query } = URL.parse(url);    // 解析url
          console.log(`url is: ${protocol}://${host}${pathname}${search}`)
        }
      }).catch(err => console.error('An error occurred', err));
    }
    

    但是,该方法仅在app启动时触发,若需要在app开启期间(位于后台)处理跳转到App的链接,需要用另一个方法来监听

    import URL from 'url';
    componentDidMount() {
      Linking.addEventListener('url', this._handleOpenURL);
    },
    componentWillUnmount() {
      Linking.removeEventListener('url', this._handleOpenURL);
    },
    handleURL(event) {
      const { protocol, host, pathname, search, query } = URL.parse(event.url);    // 解析url
      console.log(`url is: ${protocol}://${host}${pathname}${search}`)
    }
    

    相关文章

      网友评论

          本文标题:React Native通过Linking接收并处理App Li

          本文链接:https://www.haomeiwen.com/subject/kmlqoctx.html