首页 > 解决方案 > 即使 JSON 文件没有链接,React Native 站点也会显示单词 Online

问题描述

我有这个移动应用程序页面,其中显示了我公司提供的服务及其地址。如果服务有网址,则应在移动应用程序上显示“在线”一词,如果没有,则不应显示在线一词。我正在使用 flatlist 显示服务。以下是我的代码的一部分,如果服务存在或不存在,则显示“在线”字样。

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


<View style={styles.AddressRow}>
                            {
                                    item.Online != ''? <TouchableOpacity  onPress={() => Linking.openURL(  item.Online )}>
                                    </TouchableOpacity>: null 

                             }


                          <TouchableOpacity  onPress={() => Linking.openURL(item.Online)}>
                                            <Text style={styles.underLineText}>Online</Text>
                         </TouchableOpacity>

我的 JSON 文件如下所示:

[


    {
        "id":"1",
        "fk": 1,
        "addr": "Test Drive",
        "phone": "951-955-6200",
        "LatL":"33.9",
        "Long2":"-117.373423",
        "Online": "http://www.test.com",

        "image" : "png"
     },



     {
        "id":"3",
        "fk": 1,
        "addr": "1234 Test drive",
        "phone": "951-955-6200",
        "LatL":"33.7",
        "Long2":"-116.971169",
        "Online": "",
        "image" : "Home"


     }
]

即使 JSON 文件中的 Online 为空,除了在线单词显示之外,所有内容都正确显示:“在线”:“”,

任何帮助将不胜感激。

标签: react-native

解决方案


如果使用逻辑运算符,您似乎正在尝试进行内联

<View style={styles.AddressRow}>
  {item.Online !== '' && <TouchableOpacity  onPress={() => Linking.openURL(item.Online)}>
    <Text style={styles.underLineText}>Online</Text>
  </TouchableOpacity>}

https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

或者,您可以使用条件运算符执行内联 If-Else

<View style={styles.AddressRow}>
  {item.Online !== '' ? (<TouchableOpacity  onPress={() => Linking.openURL(item.Online)}>
      <Text style={styles.underLineText}>Online</Text>
    </TouchableOpacity>) : null}

https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator


推荐阅读