code

React Native App에 하이퍼 링크 표시

codestyles 2020. 10. 28. 08:06
반응형

React Native App에 하이퍼 링크 표시


React Native 앱에서 하이퍼 링크를 어떻게 표시하나요?

예 :

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

이 같은:

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

LinkingReact Native와 함께 제공되는 모듈을 사용합니다 .


선택한 답변은 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'
  }
});

이를 위해 Text컴포넌트를 TouchableOpacity. a TouchableOpacity를 터치하면 희미 해집니다 (덜 불투명 해짐). 이것은 사용자가 텍스트를 터치 할 때 즉각적인 피드백을 제공하고 개선 된 사용자 경험을 제공합니다.

onPress속성 TouchableOpacity을 사용하여 링크를 만들 수 있습니다 .

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

React Native 문서는 다음을 사용하도록 제안합니다 Linking.

참고

다음은 매우 기본적인 사용 사례입니다.

import { Linking } from 'react-native';

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

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

딜러가 선택한 기능 또는 클래스 구성 요소 표기법을 사용할 수 있습니다.


React Native의 경우 App에서 Hyperlink를 여는 라이브러리가 있습니다. https://www.npmjs.com/package/react-native-hyperlink

이 외에도 URL을 확인해야하며 가장 좋은 방법은 Regex입니다. https://www.npmjs.com/package/url-regex


React Native Hyperlink (Native <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>

링크 및 기타 유형의 리치 텍스트를 수행하려는 경우보다 포괄적 인 솔루션은 React Native HTMLView 를 사용하는 것 입니다.


문자열 내에 포함 된 링크 를 사용하여 지금이 문제를 발견하는 모든 사람과 내 해키 솔루션을 공유 할 것이라고 생각했습니다 . 문자열이 공급되는 모든 것을 동적으로 렌더링 하여 링크인라인 하려고 시도 합니다.

Please feel free to tweak it to your needs. It's working for our purposes as such:

This is an example of how https://google.com would appear.

View it on 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;
}

참고URL : https://stackoverflow.com/questions/30540252/display-hyperlink-in-react-native-app

반응형