React Native Uygulamasında Köprü Nasıl Görüntülenir?


112

Bir React Native uygulamasında bir köprüyü nasıl görüntülerim?

Örneğin

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

2
Kullanıcıların daha fazla dikkatini çekmek için 'javascript' gibi daha fazla etiket eklemeyi düşünün. Ancak, 'kodlama' vb. Etiketler ekleyerek gönderilerinizi aşırı genellemeyin
Matt C

@MattC 'javascript' eklemenin çok genel olduğunu iddia ediyorum.
ryanwebjackson

Yanıtlar:


242

Bunun gibi bir şey:

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

LinkingReact Native ile birlikte verilen modülü kullanarak .


1
Dinamik bir değere ihtiyacınız varsa this.props.url, bunun yerine 'http://google.com'(parantez gerekmez) gibi bir şey kullanabilirsiniz
Elon Zito

@philipp bana hata veriyor m 'değişken Bağlama bulamıyor'
Devansh sadhotra

2
@devanshsadhotra import { Linking } from 'react-native';belgenizde var mı?
Eric Phillips

2
<Metin> öğelerini de gömebilirsiniz, böylece bağlantılı metin ana metnin bir bölümü olabilir:<Text>Some paragraph <Text onPress=...>with a link</Text> inside</Text>
pstanton

4
LinkingIOS amortismana tabi tutuldu, Linking'i kullanın.
jasonleonhard

26

Seçilen cevap yalnızca iOS ile ilgilidir. Her iki platform için aşağıdaki bileşeni kullanabilirsiniz:

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

3
Seçilen cevap Android'de benim için iyi çalıştı (RN 35).
Pedram

2
@JacobLauritzen, şimdi biri cevabımı kopyaladıktan sonra aynı: / stackoverflow.com/posts/30540502/revisions
Kuf

21

Bunu yapmak için, bir Textbileşeni bir TouchableOpacity. A TouchableOpacitydokunulduğunda, kaybolur (daha az opak hale gelir). Bu, kullanıcıya metne dokunduğunda anında geri bildirim verir ve gelişmiş bir kullanıcı deneyimi sağlar.

Bağlantının gerçekleşmesi için onPressmülkü kullanabilirsiniz TouchableOpacity:

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

13

React Native belgeleri Linkingşunları kullanmanızı önerir :

Referans

İşte çok basit bir kullanım örneği:

import { Linking } from 'react-native';

const url="https://google.com"

<Text onPress={() => Linking.openURL(url)}>
    {url}
</Text>

Bayi seçimini, işlevsel veya sınıf bileşen gösterimini kullanabilirsiniz.


LinkingIOS amortismana tabi tutuldu, Linking'i kullanın.
jasonleonhard

4

React Yerel Köprüsünü (Yerel <A>etiket) kullanın:

Yüklemek:

npm i react-native-a

ithalat:

import A from 'react-native-a'

Kullanım:

  1. <A>Example.com</A>
  2. <A href="example.com">Example</A>
  3. <A href="https://example.com">Example</A>
  4. <A href="example.com" style={{fontWeight: 'bold'}}>Example</A>

3

Yukarıdaki yanıtlara eklenecek bir başka yararlı not, bazı flexbox stilleri eklemektir. Bu, metni tek satırda tutacak ve metnin ekranla çakışmamasını sağlayacaktır.

 <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>


1

Bağlantılar ve diğer zengin metin türlerini yapmak istiyorsanız, daha kapsamlı bir çözüm React Native HTMLView kullanmaktır .


1
Bu bağlantı soruyu cevaplayabilirken, cevabın temel kısımlarını buraya eklemek ve referans için bağlantıyı sağlamak daha iyidir. Bağlantılı sayfa değişirse, yalnızca bağlantı yanıtları geçersiz hale gelebilir. - Yorumdan
Ari0nhh

@ Ari0nhh Yorumunuza yanıt verebilmemin tek yolu olduğu için soruyu geri aldım. SO'da yüksek dereceli bir cevabın sadece iyi bir kitaplığa bağlantı olduğu birçok örnek vardır. Ayrıca diğer yanıtlar zaten basit bir uygulamayı kapsamaktadır. Sanırım bunu orijinal soruya bir yorum olarak yeniden gönderebilirim, ancak bunu gerçek bir cevap olarak görüyorum. Ve buradaki bağlantıyı bırakmak, insanlar onu düzenlemek ve daha iyi örneklerle geliştirmek istiyorsa, en azından şimdi başlamak için bir yer var.
Eliot

1

Hacky çözümümü şimdi bir dizedeki gömülü bağlantılarla bu sorunu keşfeden herkesle paylaşacağımı düşündüm . Bağlantıları , içine hangi dizge beslenirse onu dinamik olarak oluşturarak satır içi yapmaya çalışır .

Lütfen ihtiyaçlarınıza göre ince ayar yapmaktan çekinmeyin. Bizim amaçlarımız için çalışıyor:

Bu, https: //google.com'un nasıl görüneceğine dair bir örnektir .

Gist'te görüntüleyin:

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;
}

1

Modülün React Native'den Bağlanması

import { TouchableOpacity, Linking } from "react-native";

Dene:-

<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
     <Text> Facebook </Text>     
</TouchableOpacity>

0

<Text style = {{color: 'skyblue'}} onPress = {() => Linking.openURL ('http://yahoo.com')}> Yahoo bağlantı özelliğini kullanabilirsiniz

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.