我是react-native的新手,我想在默认浏览器(如Android和iPhone中的Chrome)中打开url。我们通过在Android的意图一样的功能,我想实现的打开网址。我已经搜索了很多次,但它会给予我的结果 Deepklinking.
dy2hfwbg1#
您应该使用Linking。来自文档的示例:
Linking
class OpenURLButton extends React.Component { static propTypes = { url: React.PropTypes.string }; handleClick = () => { Linking.canOpenURL(this.props.url).then(supported => { if (supported) { Linking.openURL(this.props.url); } else { console.log("Don't know how to open URI: " + this.props.url); } }); }; render() { return ( <TouchableOpacity onPress={this.handleClick}> {" "} <View style={styles.button}> {" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "} </View> {" "} </TouchableOpacity> ); } }
下面是一个可以在Expo Snack上尝试的示例:
import React, { Component } from 'react'; import { View, StyleSheet, Button, Linking } from 'react-native'; import { Constants } from 'expo'; export default class App extends Component { render() { return ( <View style={styles.container}> <Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', }, });
vxqlmq5t2#
这是一种更简单的方法,无需检查应用程序是否可以打开URL。
loadInBrowser = () => { Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err)); };
用一个按钮呼叫它。
<Button title="Open in Browser" onPress={this.loadInBrowser} />
ippsafx73#
试试这个:
import React, { useCallback } from "react"; import { Linking } from "react-native"; OpenWEB = () => { Linking.openURL(url); }; const App = () => { return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>; };
希望这能解决你的问题。
h9a6wy2h4#
在React 16.8+中,可使用以下代码创建ExternalLinkBtn组件,类似于Web上的a标记。链接将在外部默认浏览器中打开。
ExternalLinkBtn
a
import React from 'react'; import { Button, Linking } from 'react-native'; const ExternalLinkBtn = (props) => { return <Button title={props.title} onPress={() => { Linking.openURL(props.url) .catch(err => { console.error("Failed opening page because: ", err) alert('Failed to open page') })}} /> }
下面是在组件中使用ExternalLinkBtn的示例
export default function exampleUse() { return ( <View> <ExternalLinkBtn title="Example Link" url="https://example.com" /> </View> ) }
4条答案
按热度按时间dy2hfwbg1#
您应该使用
Linking
。来自文档的示例:
下面是一个可以在Expo Snack上尝试的示例:
vxqlmq5t2#
这是一种更简单的方法,无需检查应用程序是否可以打开URL。
用一个按钮呼叫它。
ippsafx73#
试试这个:
希望这能解决你的问题。
h9a6wy2h4#
在React 16.8+中,可使用以下代码创建
ExternalLinkBtn
组件,类似于Web上的a
标记。链接将在外部默认浏览器中打开。下面是在组件中使用
ExternalLinkBtn
的示例