【问题标题】:Detect link and return another view in react native检测链接并在本机反应中返回另一个视图
【发布时间】:2019-11-11 11:54:39
【问题描述】:

我的代码:

const orderResultJson = [
  {
    key: 'Скачайте приложение по ссылке',
    value: 'https://google.com'
  },
  {
    key: 'Логин',
    value: 'https://instagram.com'
  },
  {
    key: 'Пароль',
    value: '849846'
  },
];

function DetailsSection({ item }){
  return(
     <View>
        <Text>{item.key}</Text>
        <Text> {replaceURLWithHTMLLinks(item.value) ? 'Cсылка' : 'No'} </Text>
    </View>
  )
}
  function replaceURLWithHTMLLinks(text)
    {
        var expression =  
/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi; 
        var regex = new RegExp(expression); 
        var url = text; 
        url.match(regex) ? true : false;

} 

render() {
    return (
     ........
        <FlatList
          .......
          renderItem={({item}) => <DetailsSection item={item} />} 
          keyExtractor={item => item.key} 
        />
      .....
}

我在 DetailsS​​ection 函数中有一个条件。逻辑如下:

如果 {item.value} 包含链接,则显示“一些随机文本”

如果不是,就显示什么是“否”

目前,我还没有完全理解这个问题。一切似乎都运行良好,但 DetailsS​​ection 中的条件流仅显示没有。但在 JSON 中,我确实有超链接。有什么建议吗?

【问题讨论】:

    标签: javascript json reactjs react-native hyperlink


    【解决方案1】:

    也许你错过了 replaceURLWithHTMLLinks 函数中的 'return' 语句:

    ...
    return !!url.match(regex);
    ...
    

    【讨论】:

      【解决方案2】:

      我认为您使用的正则表达式不允许在 URL 的开头使用 https://。而且您忘记了从函数中返回布尔值。试试这个:

      function replaceURLWithHTMLLinks(text)
          {
              var expression =  /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi; 
              var regex = new RegExp(expression); 
              var url = text; 
              return url.match(regex) ? true : false;
      
      } 
      

      【讨论】:

        猜你喜欢
        • 2016-02-08
        • 1970-01-01
        • 1970-01-01
        • 2018-03-28
        • 2017-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多