How does one Display a Hyperlink in React Native App?

前端 未结 11 1198
孤街浪徒
孤街浪徒 2020-12-12 16:38

How do I display a hyperlink in a React Native app?

e.g.

Google 
11条回答
  •  抹茶落季
    2020-12-12 17:17

    Just thought I'd share my hacky solution with anyone who's discovering this problem now with embedded links within a string. It attempts to inline the links by rendering it dynamically with what ever string is fed into it.

    Please feel free to tweak it to your needs. It's working for our purposes as such:

    This is an example of how https://google.com would appear.

    View it on Gist:

    https://gist.github.com/Friendly-Robot/b4fa8501238b1118caaa908b08eb49e2

    import React from 'react';
    import { Linking, Text } from 'react-native';
    
    export default function renderHyperlinkedText(string, baseStyles = {}, linkStyles = {}, openLink) {
      if (typeof string !== 'string') return null;
      const httpRegex = /http/g;
      const wwwRegex = /www/g;
      const comRegex = /.com/g;
      const httpType = httpRegex.test(string);
      const wwwType = wwwRegex.test(string);
      const comIndices = getMatchedIndices(comRegex, string);
      if ((httpType || wwwType) && comIndices.length) {
        // Reset these regex indices because `comRegex` throws it off at its completion. 
        httpRegex.lastIndex = 0;
        wwwRegex.lastIndex = 0;
        const httpIndices = httpType ? 
          getMatchedIndices(httpRegex, string) : getMatchedIndices(wwwRegex, string);
        if (httpIndices.length === comIndices.length) {
          const result = [];
          let noLinkString = string.substring(0, httpIndices[0] || string.length);
          result.push({ noLinkString });
          for (let i = 0; i < httpIndices.length; i += 1) {
            const linkString = string.substring(httpIndices[i], comIndices[i] + 4);
            result.push(
               openLink(linkString) : () => Linking.openURL(linkString)}
              >
                { linkString }
              
            );
            noLinkString = string.substring(comIndices[i] + 4, httpIndices[i + 1] || string.length);
            if (noLinkString) {
              result.push(
                
                  { noLinkString }
                
              );
            }
          }
          // Make sure the parent `` container has a style of `flexWrap: 'wrap'`
          return result;
        }
      }
      return { string };
    }
    
    function getMatchedIndices(regex, text) {
      const result = [];
      let match;
      do {
        match = regex.exec(text);
        if (match) result.push(match.index);
      } while (match);
      return result;
    }
    

提交回复
热议问题