我希望用户能够从评论(字符串)中获取链接,类似于linkify。有一个简单的方法吗?我相信它在这里得到解决(https://github.com/facebook/react-native/issues/3148),但我不太确定如何实现它。谢谢。
答案 0 :(得分:5)
您可以使用react-native-hyperlink:
import Hyperlink from 'react-native-hyperlink'
import {Text, Linking} from 'react-native'
const MyComponent = () => (
<Hyperlink onPress={Linking.openURL}>
<Text>{"Click on https://stackoverflow.com to test"}</Text>
</Hyperlink>
)
答案 1 :(得分:4)
我根据quick demo中的组件制作了link。
我无法在该环境中测试LinkingIOS,但这些docs应该可以帮助您。
以下是原始资料来源:
var HyperText = React.createClass({
render: function() {
// Check if nested content is a plain string
if (typeof this.props.children === 'string') {
// Split the content on space characters
var words = this.props.children.split(/\s/);
// Loop through the words
var contents = words.map(function(word, i) {
// Space if the word isn't the very last in the set, thus not requiring a space after it
var separator = i < (words.length - 1) ? ' ' : '';
// The word is a URL, return the URL wrapped in a custom <Link> component
if (word.match(/^https?\:\//)) {
return <Link key={i} url={word}>{word}{separator}</Link>;
// The word is not a URL, return the word as-is
} else {
return word + separator;
}
});
// The nested content was something else than a plain string
// Return the original content wrapped in a <Text> component
} else {
console.log('Attempted to use <HyperText> with nested components. ' +
'This component only supports plain text children.');
return <Text>{this.props.children}</Text>;
}
// Return the modified content wrapped in a <Text> component
return (
<Text>
{contents}
</Text>
);
}
});
var Link = React.createClass({
render: function() {
return <Text onPress={this.openUrl.bind(this, this.props.url)}>{this.props.children}</Text>;
},
openUrl: function(url) {
LinkingIOS.canOpenURL(url, (supported) => {
if (!supported) {
AlertIOS.alert('Can\'t handle url: ' + url);
} else {
LinkingIOS.openURL(url);
}
});
}
});
希望这有点帮助。
答案 2 :(得分:1)
尝试使用此库{{3}},它可以检测到它是hyperlink
,hashtag
,mention
,email
还是{{1} }。
phone number
答案 3 :(得分:0)
您可以使用此包将字符串转换为链接 https://www.npmjs.com/package/react-linkify
<Linkify>
See source code at https://github.com/tasti/react-linkify/.
</Linkify>
它将呈现