【问题标题】:React Native add bold or italics to single words in <Text> fieldReact Native 为 <Text> 字段中的单个单词添加粗体或斜体
【发布时间】:2016-06-13 14:08:57
【问题描述】:

如何将文本字段中的单个单词设为粗体或斜体?有点像这样:

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

如果我为粗体字符创建一个新的文本字段,它将把它分隔到另一行,所以这肯定不是这样做的方法。这就像在 标签中创建一个 标签只是为了使一个单词变粗。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您可以将&lt;Text&gt; 用作其他文本组件的容器。 这是一个例子:

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

    这是example

    【讨论】:

    • 是的,但就像我说的那样,这是行不通的,因为每个文本元素都被分隔到不同的行中。
    • 如果将&lt;Text style={{fontWeight: 'bold'}}&gt; with&lt;/Text&gt; 拆分为三个单独的行,则会丢失前导空格,因此您可能需要使用{' with'} 来确保始终拥有它。
    • 只想指出,如果你styled-components,你可以传递一个粗体property
    • @KonstantinYakushin 链接已损坏,仅供参考
    • @kevlarjacket 是的。不幸的是,rnplay 服务已关闭。我会尝试更新示例。
    【解决方案2】:

    为了更接近网络的感觉:

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

    【讨论】:

    • 这不适用于具有字符串值的变量
    • 就像我所说的网络一样 - 使用 &lt;Strong&gt; 而不是 &lt;B&gt; :)
    • 在iOS和Android上会崩溃,你不能在中使用标签
    • 您可以将const B = this.B 添加到render
    • @Hakan - reactnative.dev/docs/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. 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',
      },
     
    });

    【讨论】:

    • 感谢分享 ParsedText!辉煌
    • 欢迎各位。快乐编码
    • 动态文本怎么办
    【解决方案4】:

    它不在要求的文本字段中,但将单独的文本元素包装到视图中会产生所需的输出。如果您不想将另一个库添加到项目中只是为了设置一些文本的样式,则可以使用此方法。

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

    结果如下

    【讨论】:

      【解决方案5】:

      使用这个react native library

      安装

      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

      【讨论】:

        【解决方案6】:

        您也可以将一个 Text 标签放在另一个 Text 标签内。第二个文本标签将继承第一个文本标签的样式,但您可以保持独立于其父标签的样式。

        <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",
          }
        
        

        【讨论】:

          【解决方案7】:

          您可以只嵌套具有所需样式的 Text 组件。该样式将与第一个 Text 组件中已定义的样式一起应用。

          例子:

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

          【讨论】:

            【解决方案8】:

            我是react-native-spannable-string的维护者

            具有自定义样式的嵌套&lt;Text/&gt; 组件效果很好,但可维护性较低。

            我建议你用这个库构建这样的可跨字符串。

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

            【讨论】:

              【解决方案9】:

              粗体字:

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

              【讨论】:

                【解决方案10】:

                例如!

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

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

                【讨论】:

                  【解决方案11】:
                  <Text>
                      <Text style={{fontWeight: "bold"}}>bold</Text>
                      normal text
                      <Text style={{fontStyle: "italic"}}> italic</Text>
                  </Text>
                  

                  【讨论】:

                  • 最好为您的代码添加一些解释
                  【解决方案12】:

                  现在无法嵌套文本组件,但您可以将文本包装在视图中,如下所示:

                  <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 来实现。希望对您有所帮助。

                  【讨论】:

                    猜你喜欢
                    • 2023-03-20
                    • 2014-04-29
                    • 2018-11-06
                    • 2016-12-13
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-09-04
                    相关资源
                    最近更新 更多