【问题标题】:How does one Display a Hyperlink in React Native App?如何在 React Native App 中显示超链接?
【发布时间】:2015-08-12 22:48:13
【问题描述】:

如何在 React Native 应用程序中显示超链接?

例如

<a href="https://google.com>Google</a> 

【问题讨论】:

  • 考虑添加更多标签,例如“javascript”,以获得更多用户的关注。但不要通过添加“编码”等标签来过度概括您的帖子。
  • @MattC 我认为添加“javascript”过于笼统。

标签: javascript react-native


【解决方案1】:

类似这样的:

<Text style={{color: 'blue'}}
      onPress={() => Linking.openURL('http://google.com')}>
  Google
</Text>

使用与 React Native 捆绑的 Linking 模块。

import { Linking } from 'react-native';

【讨论】:

  • 如果需要动态值,可以使用 this.props.url 代替 'http://google.com'(无需大括号)
  • @philipp 它向我抛出错误 m '找不到变量链接'
  • @devanshsadhotra 你的文档中有import { Linking } from 'react-native';吗?
  • 您也可以嵌入 元素,以便链接文本可以成为父文本的一部分:&lt;Text&gt;Some paragraph &lt;Text onPress=...&gt;with a link&lt;/Text&gt; inside&lt;/Text&gt;
  • LinkingIOS 已被贬值,请使用 Linking。
【解决方案2】:

所选答案仅适用于 iOS。对于这两个平台,您都可以使用以下组件:

import React, { Component, PropTypes } from 'react';
import {
  Linking,
  Text,
  StyleSheet
} from 'react-native';

export default class HyperLink extends Component {

  constructor(){
      super();
      this._goToURL = this._goToURL.bind(this);
  }

  static propTypes = {
    url: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  }

  render() {

    const { title} = this.props;

    return(
      <Text style={styles.title} onPress={this._goToURL}>
        >  {title}
      </Text>
    );
  }

  _goToURL() {
    const { url } = this.props;
    Linking.canOpenURL(url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log('Don\'t know how to open URI: ' + this.props.url);
      }
    });
  }
}

const styles = StyleSheet.create({
  title: {
    color: '#acacac',
    fontWeight: 'bold'
  }
});

【讨论】:

【解决方案3】:

为此,我强烈考虑将Text 组件包装在TouchableOpacity 中。当TouchableOpacity 被触摸时,它会消失(变得不那么不透明)。这样可以在用户触摸文本时立即获得反馈,并提供改进的用户体验。

您可以使用TouchableOpacity 上的onPress 属性来实现链接:

<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
  <Text style={{color: 'blue'}}>
    Google
  </Text>
</TouchableOpacity>

【讨论】:

    【解决方案4】:

    React Native 文档建议使用 Linking:

    Reference

    这是一个非常基本的用例:

    import { Linking } from 'react-native';
    
    const url="https://google.com"
    
    <Text onPress={() => Linking.openURL(url)}>
        {url}
    </Text>
    

    您可以使用函数式或类组件表示法,由经销商选择。

    【讨论】:

    • LinkingIOS 已被贬值,请使用 Linking。
    【解决方案5】:

    添加到上述响应中的另一个有用的注释是添加一些 flexbox 样式。 这将使文本保持在一行,并确保文本不会与屏幕重叠。

     <View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
      <Text>Add your </Text>
      <TouchableOpacity>
        <Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
             link
        </Text>
       </TouchableOpacity>
       <Text>here.
       </Text>
     </View>
    

    【讨论】:

      【解决方案6】:

      使用 React Native 超链接(原生 &lt;A&gt; 标签):

      安装:

      npm i react-native-a
      

      导入:

      import A from 'react-native-a'
      

      用法:

      1. &lt;A&gt;Example.com&lt;/A&gt;
      2. &lt;A href="example.com"&gt;Example&lt;/A&gt;
      3. &lt;A href="https://example.com"&gt;Example&lt;/A&gt;
      4. &lt;A href="example.com" style={{fontWeight: 'bold'}}&gt;Example&lt;/A&gt;

      【讨论】:

        【解决方案7】:

        对于 React Native,有一个库可以在 App 中打开超链接。 https://www.npmjs.com/package/react-native-hyperlink

        除此之外,我想您还需要检查 url,最好的方法是正则表达式。 https://www.npmjs.com/package/url-regex

        【讨论】:

        【解决方案8】:

        只是想与现在发现此问题的任何人分享我的 hacky 解决方案,并在字符串中使用 嵌入式链接。它尝试内联链接,方法是使用输入的字符串动态呈现链接。

        请随时根据您的需要对其进行调整。它为我们的目的而工作:

        这是https://google.com 将如何出现的示例。

        在 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(<Text key={noLinkString} style={baseStyles}>{ noLinkString }</Text>);
              for (let i = 0; i < httpIndices.length; i += 1) {
                const linkString = string.substring(httpIndices[i], comIndices[i] + 4);
                result.push(
                  <Text
                    key={linkString}
                    style={[baseStyles, linkStyles]}
                    onPress={openLink ? () => openLink(linkString) : () => Linking.openURL(linkString)}
                  >
                    { linkString }
                  </Text>
                );
                noLinkString = string.substring(comIndices[i] + 4, httpIndices[i + 1] || string.length);
                if (noLinkString) {
                  result.push(
                    <Text key={noLinkString} style={baseStyles}>
                      { noLinkString }
                    </Text>
                  );
                }
              }
              // Make sure the parent `<View>` container has a style of `flexWrap: 'wrap'`
              return result;
            }
          }
          return <Text style={baseStyles}>{ string }</Text>;
        }
        
        function getMatchedIndices(regex, text) {
          const result = [];
          let match;
          do {
            match = regex.exec(text);
            if (match) result.push(match.index);
          } while (match);
          return result;
        }
        

        【讨论】:

          【解决方案9】:

          从 React Native 导入链接模块

          import { TouchableOpacity, Linking } from "react-native";
          

          试试看:-

          <TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
               <Text> Facebook </Text>     
          </TouchableOpacity>
          

          【讨论】:

            【解决方案10】:

            Linking.openURL('http://yahoo.com')}> https://google.com

            上面的代码会让你的文本看起来像超链接

            【讨论】:

              【解决方案11】:

              如果你想做链接等类型的富文本,更全面的解决方案是使用React Native HTMLView

              【讨论】:

              • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
              • @Ari0nhh 我没有删除这个问题,因为这是我回复您评论的唯一方法。 SO上有很多先例,其中排名靠前的答案只是指向一个好的图书馆的链接。加上其他答案已经涵盖了一个简单的实现。我想我可以将其重新发布为对原始问题的评论,但我确实将其视为真正的答案。如果人们想编辑它并用更好的例子改进它,至少现在有一个地方可以开始。
              【解决方案12】:

              您可以使用链接属性 Linking.openURL('http://yahoo.com')}> 雅虎

              【讨论】:

                【解决方案13】:

                我能够使用以下方法将可触摸的子字符串与周围的文本对齐。固定边距数字有点笨拙,但如果您不需要将其与多个字体大小一起使用,那就足够了。否则,您可以将边距作为道具与BaseText 组件一起传递。

                import styled, { StyledComponent } from 'styled-components'
                import { View, Linking, Text, TouchableOpacity } from 'react-native'
                
                type StyledTextComponent = StyledComponent<typeof Text, any, {}, never>
                
                export interface TouchableSubstringProps {
                  prefix: string
                  substring: string
                  suffix: string
                  BaseText: StyledTextComponent
                  onPress: () => void
                }
                
                export const TouchableSubstring = ({
                  prefix,
                  substring,
                  suffix,
                  BaseText,
                  onPress,
                }: TouchableSubstringProps): JSX.Element => {
                  const UnderlinedText = styled(BaseText)`
                    text-decoration: underline;
                    color: blue;
                  `
                
                  return (
                    <TextContainer>
                      <Text>
                        <BaseText>{prefix}</BaseText>
                        <TextAlignedTouchableOpacity onPress={onPress}>
                          <UnderlinedText>{substring}</UnderlinedText>
                        </TextAlignedTouchableOpacity>
                        <BaseText>{suffix}</BaseText>
                      </Text>
                    </TextContainer>
                  )
                }
                
                const TextContainer = styled(View)`
                  display: flex;
                  flex: 1;
                  flex-direction: row;
                  flex-wrap: wrap;
                  margin: 10px;
                `
                
                const TextAlignedTouchableOpacity = styled(TouchableOpacity)`
                  margin-top: 1px;
                  margin-bottom: -3px;
                `
                
                

                【讨论】:

                  猜你喜欢
                  • 2018-05-14
                  • 2021-12-14
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多