2017-08-17 93 views
2

我想通過更改文本的背景色來突出顯示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://stackoverflow.com/questions/16597304/background-color-for-text-only – Felipe

回答

0

我相信問題是組件上的display css屬性。

你的分量似乎與呈遞display: block;代替display: inline;

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

+0

我認爲React本機不支持內聯顯示(僅限柔性)。越接近我可以得到的是flexWrap屬性,但它似乎沒有完全相同的東西 –

0

在這裏,我已經做了,你可以看看。

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組件相同的方式進行包裝:/ –

相關問題