【问题标题】:React Native : How to open a specific URL with onPress function from an array of urls?React Native:如何从 url 数组中使用 onPress 函数打开特定的 URL?
【发布时间】:2018-12-06 10:40:03
【问题描述】:

我有一个这样的网址数组:

 [ "https://hey.com",
   "https://yes.com",
   "https://wow.com",
      /..
 ]

我有相同的图标但多次。我希望他们每个人都在按下时重定向到其特定的网址。

我试过这段代码,但它不起作用:

onPress=(arrayOfURL)=>{  
for (i in arrayOfURL)
{      
  this.setState({ browserOpen: true });
  WebBrowser.openBrowserAsync(JSON.stringify(arrayOfURL[i]))
  .then(() => {
        WebBrowser.dismissBrowser();
        this.setState({ browserOpen: false });
    });         
}

}

图标代码:

          <View >         
            <Icon
              name='sc-telegram'
              type='evilicon'
              color='black'          
              onPress={this.onPress} />
          </View>

【问题讨论】:

  • 你能在你有图标的地方添加代码部分并调用onPress()吗?
  • 我做到了。你有提示吗?
  • 我刚刚注意到你写的是 arrayOfURI[i] 而不是 arrayOfURL[i]。是浏览器打开还是问题所在?
  • 不,抱歉,这只是一个错误。我的浏览器打不开。我认为问题在于每次按下图标时,函数都会循环并尝试打开数组中的每个 URL
  • 它肯定会尝试打开每个 URL,这不是你的目标吗?

标签: arrays react-native url onpress


【解决方案1】:

快速帮助!没有测试过代码,但这就是我所做的。

const urls = ["https://hey.com", "https://yes.com", "https://wow.com"];

urls.map(value => {
 return <View>         
            <Icon
              name='sc-telegram'
              type='evilicon'
              color='black'          
              onPress={() => this.openSpecificUrl(value)} />
          </View>

})

onSpecificUrl = (specificUrl) => {
  //you will get specific url from an array. You can perform your opening logic here
}

【讨论】:

  • 我试过了。我得到'未定义不是一个函数..near urls.map..'
【解决方案2】:

看来你在做一个逻辑错误。您不需要 for 循环,只需通过每个图标调用 onPress() 方法传递一个参数来指定您要打开的链接:

<Icon
     name='sc-telegram'
     type='evilicon'
     color='black'          
     onPress={() => this.onPress(arrayOfURL[0])} />

然后简单地说:

onPress = (url) => {
  [...]
  WebBrowser.openBrowserAsync(url).then(...)
  [...]
}

如果您的问题是如何动态地将您的链接分配给图标...那么这只是另一个问题。我希望这次我没有误解一切,这可以帮助您解决疑惑。

【讨论】:

  • 你成功了。我的大问题是动态分配,因为我只有一个图标但多次,所以我不能像onPress={() =&gt; this.onPress(arrayOfURL[0])} /&gt; 那样调用 onPress
  • 所以,我认为@Neel 的回答是正确的。一旦你定义了你的 url 数组,在 render 方法中用正确的名字映射它(你必须放置你的图标)。
猜你喜欢
  • 2017-12-25
  • 2017-09-01
  • 1970-01-01
  • 2017-11-15
  • 2021-09-15
  • 1970-01-01
  • 2017-02-16
  • 2010-11-02
  • 2017-12-06
相关资源
最近更新 更多