在默认Web浏览器中打开URL

时间:2017-05-05 11:39:37

标签: android ios react-native

我是反应原生的新手,我想在默认浏览器中打开网址,例如Android和iPhone中的Chrome

我们通过Android中的意图打开网址,就像我想要实现的功能一样。

我有多次搜索,但它会给我 Deepklinking 的结果。

4 个答案:

答案 0 :(得分:109)

您应该使用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',
  },
});

答案 1 :(得分:2)

试试这个:

import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
  Linking.openURL(url);
};

const App = () => {
  return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};

希望这能解决您的问题。

答案 2 :(得分:1)

在React 16.8+中,您可以使用功能组件

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')
                })}}
          />
}

export default function exampleUse() {
  return (
    <View>
      <ExternalLinkBtn title="Example Link" url="https://example.com" />
    </View>
  )
}

答案 3 :(得分:0)

一种更简单的方法,消除了检查应用程序是否可以打开网址的情况。

  loadInBrowser = () => {
    Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
  };

通过按钮调用。

<Button title="Open in Browser" onPress={this.loadInBrowser} />
相关问题