programing

네이티브 앱에서 하이퍼링크를 표시하는 방법은?

javajsp 2023. 10. 1. 19:16

네이티브 앱에서 하이퍼링크를 표시하는 방법은?

리액트 네이티브 앱에서 하이퍼링크를 표시하려면 어떻게 해야 합니까?

예.

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

이와 같은 것:

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

을 사용하여Linking리액트 네이티브와 함께 제공되는 모듈입니다.

import { Linking } from 'react-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'
  }
});

하는 것을 하고 싶습니다.TextTouchableOpacity일 때.TouchableOpacity터치하면 색이 바뀝니다(becomes 덜 불투명함).이를 통해 텍스트를 터치할 때 사용자에게 즉각적인 피드백을 제공하고 사용자 환경을 개선할 수 있습니다.

를 .onPressTouchableOpacity

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

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

위 응답에 추가할 또 다른 유용한 참고 사항은 플렉스박스 스타일링을 추가하는 것입니다.이렇게 하면 텍스트가 한 줄로 유지되고 텍스트가 화면과 겹치지 않게 됩니다.

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

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

리액트 네이티브의 경우, 앱에서 하이퍼링크를 열 수 있는 라이브러리가 있습니다.https://www.npmjs.com/package/react-native-hyperlink

이 외에도 url 확인이 필요할 것으로 생각되며 가장 좋은 접근법은 Regex입니다. https://www.npmjs.com/package/url-regex

이 그어져 웹 와 )입니다. 클릭하면 색이 바뀌는 웹 표준 동작(CSS와 같이)a:active).

import { Linking, Pressable, Text } from 'react-native';

  <Pressable onPress={() => Linking.openURL('https://example.com')}>
    {({ pressed }) =>
      <Text style={{
        textDecorationLine: 'underline',
        color: pressed ? 'red' : 'blue'
      }}>I'm a hyperlink!</Text>
    }
  </Pressable>
  • 중 는 합니다를 합니다.Text그리고.Linking와 함께TouchableOpacity, 하지만 문서에 의하면Pressable 비"다보다 "에 더 "합니다.TouchableOpacity, 그래서 우리는Pressable대신.
  • Text그 n을 있습니다.onPress()TouchableOpacity단순히 언론을 다루는 데는 불필요합니다.할 수 것 .Text

지금 이 문제를 발견하는 사람들에게 내 해킹 솔루션을 문자열 내에 포함된 링크로 공유하려고 생각했습니다.링크에 입력되는 문자열이 무엇이든 동적으로 렌더링하여 링크를 인라인화하려고 시도합니다.

필요에 따라 자유롭게 조정해 주시기 바랍니다.다음과 같은 목적으로 작동합니다.

다음은 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;
}

React Native에서 모듈 연결 가져오기

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

해보세요:-

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

<터치 가능한 불투명도 on Press={()=>Linking.openURL('http://yahoo.com ')}> <text style= {{text 데코레이션 라인: '밑줄', color: 'blue}}> https://google.com

위의 코드는 당신의 텍스트를 하이퍼링크처럼 보이게 할 것입니다.

링크 및 기타 유형의 리치 텍스트를 수행하려면 React Native HTML View를 사용하는 것이 더 포괄적인 솔루션입니다.

프레스={() => Linking.open에서 링크 속성 <Text style= {{color: 'skyblue'}을 사용하실 수 있습니다.URL('http://yahoo.com ')}> 야후

나는 다음과 같이 터치 가능한 부분 문자열과 주변 텍스트를 정렬할 수 있었습니다.고정 마진 번호는 약간 까다롭지만, 둘 이상의 글꼴 크기로 사용할 필요가 없다면 충분합니다.그렇지 않으면 여백을 소품으로 전달할 수 있습니다.BaseText요소.

import styled, { StyledComponent } from 'styled-components'
import { View, Linking, Text, TouchableOpacity } from 'react-native'

type StyledTextComponent = StyledComponent<typeof Text, any, {}, never>

export interface TouchableSubstringProps {
  prefix: string
  substring: string
  suffix: string
  BaseText: StyledTextComponent
  onPress: () => void
}

export const TouchableSubstring = ({
  prefix,
  substring,
  suffix,
  BaseText,
  onPress,
}: TouchableSubstringProps): JSX.Element => {
  const UnderlinedText = styled(BaseText)`
    text-decoration: underline;
    color: blue;
  `

  return (
    <TextContainer>
      <Text>
        <BaseText>{prefix}</BaseText>
        <TextAlignedTouchableOpacity onPress={onPress}>
          <UnderlinedText>{substring}</UnderlinedText>
        </TextAlignedTouchableOpacity>
        <BaseText>{suffix}</BaseText>
      </Text>
    </TextContainer>
  )
}

const TextContainer = styled(View)`
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
  margin: 10px;
`

const TextAlignedTouchableOpacity = styled(TouchableOpacity)`
  margin-top: 1px;
  margin-bottom: -3px;
`

언급URL : https://stackoverflow.com/questions/30540252/how-does-one-display-a-hyperlink-in-react-native-app