React Native добавить жирный шрифт или курсив к отдельным словам в поле <Text>

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

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

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

внутри тега

, чтобы выделить одно слово жирным шрифтом.

15 ответов

Решение

Ты можешь использовать <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',
  },
 
});

Вы также можете поместить текстовый тег внутри другого текстового тега. Второй текстовый тег наследует стиль первого, но вы сохраняете возможность стилизовать его независимо от его родительского.

<Text style={styles.bold}>Level: 
    <Text style={styles.normal}>Easy</Text>
</Text>

//in your stylesheet...

  bold: {
    fontSize: 25,
    fontWeight: "bold",
    color: "blue",
  },
  normal: {
  // will inherit size and color attributes
    fontWeight: "normal",
  }

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

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

Результат будет следующим

https:https://stackru.com/images/5ad06c8802bc5464d176f9c3c09ec9b96e89e053.png

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

Установить

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

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

Пример:

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

Я поддерживаю https://github.com/mym0404/react-native-spannable-string

Вложенный <Text/> компонент с нестандартным стилем работает хорошо, но ремонтопригодность низкая.

Я предлагаю вам создать такую ​​расширяемую строку с помощью этой библиотеки.

SpannableBuilder.getInstance({ fontSize: 24 })
    .append('Using ')
    .appendItalic('Italic')
    .append(' in Text')
    .build()
<Text>
    <Text style={{fontWeight: "bold"}}>bold</Text>
    normal text
    <Text style={{fontStyle: "italic"}}> italic</Text>
</Text>

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

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

Кажется, там есть один или два компонента, например react-native-markup-text, но если вы не возражаете против использования регулярных выражений для разбора небольшой разметки.

Демонстрация закусок

      import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';

/**
 * @typedef MiniMarkupTextProps
 * @type {object}
 * @property {string|null|undefined} text - a piece of mini markup text.
 * @property {object|null|undefined} itemStyle - itemStyle;
 */
export default React.memo((/** @type {MiniMarkupTextProps} */ props) => {
  const markup = props.text;
  const mappings = new Map([
    [
      'p',
      (text, index) => {
        return (
          <Text key={index} style={props.itemStyle}>
            {text}
          </Text>
        );
      },
    ],
    [
      'b',
      (text, index) => {
        return (
          <Text key={index} style={[{ fontWeight: 'bold' }, props.itemStyle]}>
            {text}
          </Text>
        );
      },
    ],
  ]);
  const keys = Array.from(mappings.keys());
  const regExp = new RegExp(
    `(${keys.map((e) => `<${e}>`).join('|')})(.*?)(${keys
      .map((e) => `<\\/${e}>`)
      .join('|')})|(\\s*)`,
    'g'
  );

  return (
    <Text>
      {markup?.match(regExp)?.map(function (tag) {
        const isEmpty = tag.trim().length === 0;
        return isEmpty ? (
          <Text>&nbsp;</Text>
        ) : (
          tag?.match(/<[a-z]>/g)?.map(function (t, index) {
            const text = tag.replace(/<[^>]+>/g, '');
            return (
              mappings.get?.(t.replace(/<|>/g, ''))?.(text, index) ?? null
            );
          })
        );
      })}
    </Text>
  );
});

Применение

        <MiniMarkupText
    text="<p>This is a simple</p> <b>test</b> <p>and it could be useful</p> <b>. Then again it all depends...</b>"
    itemStyle={{ color: 'red',  textAlign: 'center'}}
  />

Например !

const TextBold = (props) => <Text style={{fontWeight: 'bold'}}>Text bold</Text>

<Text> 123<TextBold/> </Text>

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

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

<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. Надеюсь, это поможет.

Это сработало для меня

      <h2>
{`Step ${activeStep+1}/3 - `} <strong>{stepName}</strong>
</h2>

//вывод Шаг 1/3 - Информация

Другие вопросы по тегам