Come faccio a visualizzare un collegamento ipertestuale in un'app React Native?
per esempio
<a href="https://google.com>Google</a>
Come faccio a visualizzare un collegamento ipertestuale in un'app React Native?
per esempio
<a href="https://google.com>Google</a>
Risposte:
Qualcosa come questo:
<Text style={{color: 'blue'}}
onPress={() => Linking.openURL('http://google.com')}>
Google
</Text>
utilizzando il Linkingmodulo fornito in bundle con React Native.
this.props.urlal posto di 'http://google.com'(nessuna parentesi graffa necessaria)
import { Linking } from 'react-native';nel tuo documento?
<Text>Some paragraph <Text onPress=...>with a link</Text> inside</Text>
La risposta selezionata si riferisce solo a iOS. Per entrambe le piattaforme, puoi utilizzare il seguente componente:
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'
}
});
Per fare ciò, prenderei in considerazione la possibilità di avvolgere un Textcomponente in un file TouchableOpacity. Quando a TouchableOpacityviene toccato, svanisce (diventa meno opaco). Ciò fornisce all'utente un feedback immediato quando tocca il testo e fornisce una migliore esperienza utente.
È possibile utilizzare la onPressproprietà su TouchableOpacityper rendere possibile il collegamento:
<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
<Text style={{color: 'blue'}}>
Google
</Text>
</TouchableOpacity>
Linking:import { Linking } from 'react-native';
const url="https://google.com"
<Text onPress={() => Linking.openURL(url)}>
{url}
</Text>
Usa React Native Hyperlink ( <A>tag nativo ):
Installare:
npm i react-native-a
importare:
import A from 'react-native-a'
Utilizzo:
<A>Example.com</A><A href="example.com">Example</A><A href="https://example.com">Example</A><A href="example.com" style={{fontWeight: 'bold'}}>Example</A>Un'altra nota utile da aggiungere alle risposte precedenti è l'aggiunta di uno stile flexbox. Ciò manterrà il testo su una riga e assicurerà che il testo non si sovrapponga allo schermo.
<View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
<Text>Add your </Text>
<TouchableOpacity>
<Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
link
</Text>
</TouchableOpacity>
<Text>here.
</Text>
</View>
per React Native, c'è una libreria per aprire i collegamenti ipertestuali nell'app. https://www.npmjs.com/package/react-native-hyperlink
In aggiunta a questo, suppongo che dovrai controllare l'URL e l'approccio migliore è Regex. https://www.npmjs.com/package/url-regex
Se vuoi creare link e altri tipi di rich text, una soluzione più completa è usare React Native HTMLView .
Ho solo pensato di condividere la mia soluzione hacky con chiunque stia scoprendo questo problema ora con collegamenti incorporati in una stringa. Tenta di incorporare i collegamenti rendendoli dinamicamente con qualsiasi stringa viene inserita in esso.
Sentiti libero di adattarlo alle tue esigenze. Funziona per i nostri scopi in quanto tale:
Questo è un esempio di come apparirebbe https://google.com .
Guardalo su Gist:
https://gist.github.com/Friendly-Robot/b4fa8501238b1118caaa908b08eb49e2
import React from 'react';
import { Linking, Text } from 'react-native';
export default function renderHyperlinkedText(string, baseStyles = {}, linkStyles = {}, openLink) {
if (typeof string !== 'string') return null;
const httpRegex = /http/g;
const wwwRegex = /www/g;
const comRegex = /.com/g;
const httpType = httpRegex.test(string);
const wwwType = wwwRegex.test(string);
const comIndices = getMatchedIndices(comRegex, string);
if ((httpType || wwwType) && comIndices.length) {
// Reset these regex indices because `comRegex` throws it off at its completion.
httpRegex.lastIndex = 0;
wwwRegex.lastIndex = 0;
const httpIndices = httpType ?
getMatchedIndices(httpRegex, string) : getMatchedIndices(wwwRegex, string);
if (httpIndices.length === comIndices.length) {
const result = [];
let noLinkString = string.substring(0, httpIndices[0] || string.length);
result.push(<Text key={noLinkString} style={baseStyles}>{ noLinkString }</Text>);
for (let i = 0; i < httpIndices.length; i += 1) {
const linkString = string.substring(httpIndices[i], comIndices[i] + 4);
result.push(
<Text
key={linkString}
style={[baseStyles, linkStyles]}
onPress={openLink ? () => openLink(linkString) : () => Linking.openURL(linkString)}
>
{ linkString }
</Text>
);
noLinkString = string.substring(comIndices[i] + 4, httpIndices[i + 1] || string.length);
if (noLinkString) {
result.push(
<Text key={noLinkString} style={baseStyles}>
{ noLinkString }
</Text>
);
}
}
// Make sure the parent `<View>` container has a style of `flexWrap: 'wrap'`
return result;
}
}
return <Text style={baseStyles}>{ string }</Text>;
}
function getMatchedIndices(regex, text) {
const result = [];
let match;
do {
match = regex.exec(text);
if (match) result.push(match.index);
} while (match);
return result;
}
Importa Collegamento del modulo da React Native
import { TouchableOpacity, Linking } from "react-native";
Provalo:-
<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
<Text> Facebook </Text>
</TouchableOpacity>