2015-05-29 88 views
32

如何在React Native应用程序中显示超链接?在React Native App中显示超链接

例如

<a href="https://google.com>Google</a> 
+1

考虑增加更多的标签,如“JavaScript的”从用户那里得到更多的关注。但是不要通过添加“编码”等标签来过度概括你的帖子。 –

回答

65

事情是这样的:使用Linking模块与本机作出反应是捆绑的

<Text style={{color: 'blue'}} 
     onPress={() => Linking.openURL('http://google.com')}> 
    Google 
</Text> 

。 (请注意,使用Linking需要React Native 0.20.0或更高版本。)

+0

这对我有效......谢谢! –

+0

如果你需要一个动态的值,你可以使用'this.props.url'来替代''http:// google.com''(不需要大括号) –

+0

@philipp它会抛出错误m'can' t找到变量链接' – devanshsadhotra

6

所选答案仅适用于iOS。对于这两个平台上,可以使用以下组件:

import React, { Component, PropTypes } from 'react'; 
import { 
    Linking, 
    Text, 
    StyleSheet 
} from 'react-native'; 

export default class HyperLink extends Component { 

    constructor(){ 
     super(); 
     this._goToURL = this._goToURL.bind(this); 
    } 

    static propTypes = { 
    url: PropTypes.string.isRequired, 
    title: PropTypes.string.isRequired, 
    } 

    render() { 

    const { title} = this.props; 

    return(
     <Text style={styles.title} onPress={this._goToURL}> 
     > {title} 
     </Text> 
    ); 
    } 

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

const styles = StyleSheet.create({ 
    title: { 
    color: '#acacac', 
    fontWeight: 'bold' 
    } 
}); 
+1

所选答案在Android中适用于我(RN 35)。 – Pedram

+0

这与接受的答案有何不同? –

+0

@JacobLauritzen现在好了,现在有人复制我的答案后是相同的:/ http://stackoverflow.com/posts/30540502/revisions – Kuf

0

如果你想要做的链接和其他类型的富文本的,更全面的解决方案是使用React Native HTMLView

+1

尽管这个链接可能回答这个问题,最好在这里包括答案的基本部分,提供链接供参考。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/13192218) – Ari0nhh

+0

@ Ari0nhh我放弃了这个问题,因为这是我能回应您的评论的唯一方式。在SO上有很多先例,排名靠前的答案只是链接到一个好的图书馆。加上其他答案已经涵盖了一个简单的实现我想我可以重新发布这个作为对原始问题的评论,但我确实认为它是一个真正的答案。如果人们想要编辑它并通过更好的例子来改进它,至少现在有一个地方可以开始,那么把链接留在这里对于未来的搜索者来说至少是一个缺点。 – Eliot

1

为此,我会强烈考虑将Text组件包装在TouchableOpacity中。当碰到TouchableOpacity时,它会消失(变得不透明)。这在触摸文本时给予用户即时反馈并提供改进的用户体验。

您可以使用在TouchableOpacityonPress属性,使链接发生:

<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}> 
    <Text style={{color: 'blue'}}> 
    Google 
    </Text> 
</TouchableOpacity>