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

React Native добавляет полужирный или курсив к одиночным словам в поле <Текст>

Как сделать одно слово в текстовом поле полужирным или курсивом? Вид вроде этого:

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

Если я создаю новое текстовое поле для жирного символа, оно будет разделять его на другую строку, чтобы, конечно, не способ сделать это. Это было бы похоже на создание <p> в пределах <p> чтобы сделать одно слово полужирным.

4b9b3361

Ответ 1

Вы можете использовать <Text> как контейнер для других ваших текстовых компонентов. Это пример:

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

Вот пример.

Ответ 2

Для более веб-ощущения:

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

Ответ 3

Вы можете использовать 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. [email protected]
          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',
  },
 
});

Ответ 4

Используйте эту реагирующую нативную библиотеку

Установить

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. Рендеринг пользовательских элементов

Посмотреть этот ReadMe

Ответ 5

Жирный текст:

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

Курсив:

<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontStyle: "italic"}}> with</Text>
  <Text> one word in italic</Text>
</Text>

Ответ 6

Вложение текстовых компонентов теперь невозможно, но вы можете заключить текст в представление следующим образом:

<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
    <Text>
        {'Hello '}
    </Text>
    <Text style={{fontWeight: 'bold'}}>
        {'this is a bold text '}
    </Text>
    <Text>
        and this is not
    </Text>
</View>

Я использовал строки внутри скобок, чтобы задать пробел между словами, но вы также можете добиться этого с помощью marginRight или marginLeft. Надеюсь, поможет.

Ответ 7

<Text style={{fontWeight: "500"}}> bla bla</Text>

Ответ 8

Вы можете просто вложить компоненты Text с требуемым стилем. Стиль будет применен вместе с уже определенным стилем в первом текстовом компоненте.

Пример:

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