[react-native] React Native는 <Text> 필드의 단일 단어에 굵게 또는 기울임 꼴을 추가합니다.

텍스트 필드에서 단일 단어를 굵게 또는 기울임 꼴로 만들려면 어떻게합니까? 다음과 같은 종류 :

<Text>This is a sentence <b>with</b> one word in bold</Text>

굵은 문자에 대한 새 텍스트 필드를 만들면 다른 줄로 분리되므로 확실히 그렇게하는 방법이 아닙니다. 한 단어를 굵게 만들기 위해 <p> 태그 내에 <p> 태그를 만드는 것과 같습니다.



답변

<Text>다른 텍스트 구성 요소에 대한 컨테이너처럼 사용할 수 있습니다 . 이것은 예입니다 :

...
<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontWeight: "bold"}}> with</Text>
  <Text> one word in bold</Text>
</Text>
...

여기에 예가 있습니다.


답변

웹과 같은 느낌을 원하면 :

const B = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>


답변

당신이 사용할 수있는 https://www.npmjs.com/package/react-native-parsed-text

import ParsedText from 'react-native-parsed-text';

class Example extends React.Component {
  static displayName = 'Example';

  handleUrlPress(url) {
    LinkingIOS.openURL(url);
  }

  handlePhonePress(phone) {
    AlertIOS.alert(`${phone} has been pressed!`);
  }

  handleNamePress(name) {
    AlertIOS.alert(`Hello ${name}`);
  }

  handleEmailPress(email) {
    AlertIOS.alert(`send email to ${email}`);
  }

  renderText(matchingString, matches) {
    // matches => ["[@michel:5455345]", "@michel", "5455345"]
    let pattern = /\[(@[^:]+):([^\]]+)\]/i;
    let match = matchingString.match(pattern);
    return `^^${match[1]}^^`;
  }

  render() {
    return (
      <View style={styles.container}>
        <ParsedText
          style={styles.text}
          parse={
            [
              {type: 'url',                       style: styles.url, onPress: this.handleUrlPress},
              {type: 'phone',                     style: styles.phone, onPress: this.handlePhonePress},
              {type: 'email',                     style: styles.email, onPress: this.handleEmailPress},
              {pattern: /Bob|David/,              style: styles.name, onPress: this.handleNamePress},
              {pattern: /\[(@[^:]+):([^\]]+)\]/i, style: styles.username, onPress: this.handleNamePress, renderText: this.renderText},
              {pattern: /42/,                     style: styles.magicNumber},
              {pattern: /#(\w+)/,                 style: styles.hashTag},
            ]
          }
          childrenProps={{allowFontScaling: false}}
        >
          Hello this is an example of the ParsedText, links like http://www.google.com or http://www.facebook.com are clickable and phone number 444-555-6666 can call too.
          But you can also do more with this package, for example Bob will change style and David too. foo@gmail.com
          And the magic number is 42!
          #react #react-native
        </ParsedText>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },

  url: {
    color: 'red',
    textDecorationLine: 'underline',
  },

  email: {
    textDecorationLine: 'underline',
  },

  text: {
    color: 'black',
    fontSize: 15,
  },

  phone: {
    color: 'blue',
    textDecorationLine: 'underline',
  },

  name: {
    color: 'red',
  },

  username: {
    color: 'green',
    fontWeight: 'bold'
  },

  magicNumber: {
    fontSize: 42,
    color: 'pink',
  },

  hashTag: {
    fontStyle: 'italic',
  },

});


답변

이것을 사용하십시오 반응 네이티브 라이브러리 사용

설치하기 위해서

npm install react-native-htmlview --save

기본 사용법

 import React from 'react';
 import HTMLView from 'react-native-htmlview';

  class App extends React.Component {
  render() {
   const htmlContent = 'This is a sentence <b>with</b> one word in bold';

  return (
   <HTMLView
     value={htmlContent}
   />    );
  }
}

거의 모든 html 태그를 지원합니다.

같은 고급 사용법

  1. 링크 처리
  2. 커스텀 요소 렌더링

읽어 보기보기


답변

요청한대로 텍스트 필드에 있지 않지만 별도의 텍스트 요소를보기에 래핑하면 원하는 출력을 얻을 수 있습니다. 몇 가지 텍스트 스타일링을 위해 프로젝트에 다른 라이브러리를 추가하고 싶지 않은 경우 사용할 수 있습니다.

<View style={{flexDirection: 'row'}}>
 <Text style={{fontWeight: '700', marginRight: 5}}>Contact Type:</Text>
 <Text>{data.type}</Text>
</View>

결과는 다음과 같습니다.

여기에 이미지 설명 입력


답변

여기에 이미지 설명 입력

나는 react-native-spannable-string의 관리자입니다.

<Text/>사용자 정의 스타일의 중첩 된 구성 요소는 잘 작동하지만 유지 관리 가능성이 낮습니다.

이 라이브러리를 사용하여 이와 같은 확장 가능한 문자열을 빌드하는 것이 좋습니다.

SpannableBuilder.getInstance({ fontSize: 24 })
    .append('Using ')
    .appendItalic('Italic')
    .append(' in Text')
    .build()


답변

필요한 스타일로 텍스트 구성 요소를 중첩 할 수 있습니다. 스타일은 첫 번째 텍스트 구성 요소에 이미 정의 된 스타일과 함께 적용됩니다.

예:

 <Text style={styles.paragraph}>
   Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
 </Text>