Подтвердить что ты не робот

Отображать гиперссылку в приложении React Native

Как отобразить гиперссылку в приложении React Native?

например.

<a href="#" onclick="location.href='https://google.com>Google</a> 
'; return false;
4b9b3361

Ответ 1

Примерно так:

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

используя модуль Linking, который входит в состав React Native.

Ответ 2

Выбранный ответ относится только к 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'
  }
});

Ответ 3

Для этого я настоятельно рекомендую обернуть Text компонент в TouchableOpacity. При прикосновении к TouchableOpacity он исчезает (становится менее непрозрачным). Это дает пользователю немедленную обратную связь при прикосновении к тексту и обеспечивает улучшенное взаимодействие с пользователем.

Вы можете использовать свойство onPress для TouchableOpacity чтобы ссылка появилась:

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

Ответ 4

В документации React Native предлагается использовать Linking:

Ссылка

Вот очень простой пример использования:

import { Linking } from 'react-native';

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

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

Вы можете использовать функциональную или классную нотацию компонентов, выбор дилеров.

Ответ 6

Используйте React Native Hyperlink (собственный тег <A>):

Установка:

npm i react-native-a

импорт:

import A from 'react-native-a'

Использование:

  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>

Ответ 7

Если вы хотите делать ссылки и другие типы богатого текста, более комплексное решение - использовать React Native HTMLView.

Ответ 8

Просто подумал, что поделюсь своим хакерским решением со всеми, кто сейчас обнаружит эту проблему с помощью встроенных ссылок в строке. Он пытается встроить ссылки путем динамического рендеринга с тем, что в него вводится.

Пожалуйста, не стесняйтесь настроить его под свои нужды. Это работает для наших целей как таковых:

Это пример того, как должен выглядеть https://google.com.

Посмотреть его в 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;
}