【发布时间】:2017-10-03 21:09:31
【问题描述】:
我是 react-native 的新手,我想在 Android 和 iPhone 中的 Chrome 等默认浏览器中打开 url。
我们通过 Android 中的意图打开 url,与我想要实现的功能相同。
我已经搜索了很多次,但它会给我Deepklinking的结果。
【问题讨论】:
标签: android ios react-native
我是 react-native 的新手,我想在 Android 和 iPhone 中的 Chrome 等默认浏览器中打开 url。
我们通过 Android 中的意图打开 url,与我想要实现的功能相同。
我已经搜索了很多次,但它会给我Deepklinking的结果。
【问题讨论】:
标签: android ios react-native
你应该使用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',
},
});
【讨论】:
.html 会使链接再次起作用。更新了我的答案,谢谢提醒。
一种更简单的方法,无需检查应用是否可以打开网址。
loadInBrowser = () => {
Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
};
用按钮调用它。
<Button title="Open in Browser" onPress={this.loadInBrowser} />
【讨论】:
openURL 方法之前进行检查。例如:If (this.state.url) Linking.openURL(this.state.url)。如果您不想事先检查,也可以使用 catch 子句。
在 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>
)
}
【讨论】:
试试这个:
import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
Linking.openURL(url);
};
const App = () => {
return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};
希望这能解决您的问题。
【讨论】: