如何在React Native中正确突出显示文字?

问题描述:

我想通过更改文本的背景色来突出显示React Native应用程序中的多行文本。问题在于背景颜色在整个文本区域中变化,而不仅仅是在文字之下。如何在React Native中正确突出显示文字?

class Example extends Component { 
    render() { 
    const text = '...'; 

    return (
     <View style={styles.textContainer}> 
     <Text style={styles.textStyle}> 
      {text} 
     </Text> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    textContainer: { 
    flexDirection: 'row', 
    flexWrap: 'wrap', 
    width: 200, 
    }, 
    textStyle: { 
    backgroundColor: 'red', 
    }, 
}); 

,看起来像这样上面的东西结果代码:current output

,但我想它是这样的:expected output

我可以通过拆分文本并添加得到这一结果背景颜色的单个字:

class Example extends Component { 
    render() { 
    const text = '...'; 

    const brokenText = text.split(' ').map(word => (
     <Text style={styles.textStyle}>{word} </Text> 
    )); 

    return (
     <View style={styles.textContainer}> 
     {brokenText} 
     </View> 
    ); 
    } 
} 

但是将文本分割成单个单词似乎并不是最好的解决方案并且具有巨大的性能成本。有没有更干净的方法来做到这一点?

+0

你试过使用类似文字阴影的东西吗?我不确定什么反应原生等价物会是 – Felipe

+0

@Felipe textShadow具有不同的外观(它是文本下的模糊阴影),并且对于突出显示文本不太有效:/ –

+0

是真的,我想也许用一些黑客的用法,但它没有奏效。怎么样,如果你分裂新行而不是字符,类似于此https://*.com/questions/16597304/background-color-for-text-only – Felipe

我相信问题是组件上的display css属性。

你的分量似乎与呈递display: block;代替display: inline;

见例如:https://jsfiddle.net/oorangecchicken/2qkey6o9/

+0

我认为React本机不支持内联显示(仅限柔性)。越接近我可以得到的是flexWrap属性,但它似乎没有完全相同的东西 –

在这里,我已经做了,你可以看看。

import React, { Component } from 'react'; 
import { Text, View, StyleSheet } from 'react-native'; 

export default class App extends Component { 
    render() { 
    const array =["Change code in the editor and watch it change on your phone! and fine."]; 
    return (
     <View style={styles.container}> 
     <Text> 
     {array.map(t=> (
      <Text style={styles.paragraph}>{t}</Text>))} 
     </Text> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    paddingTop: 50, 
    }, 
    paragraph: { 
    backgroundColor: 'red' 
    }, 
}); 
+0

@布鲁诺布鲁格请upvote并勾选答案。如果它帮助你,以帮助我。 –

+0

它仍然会突出显示,直到行尾(只有最后一行结束于正确的位置)。我认为内部文本(设置backgroundColor的地方)以与只是一个Text组件相同的方式进行包装:/ –