2017-05-05 66 views
3

我想要做的反應原生這種效果陣營原住民 - 有背景的文本和多行之間的間隙

Desired result

Obtained result

這是我的代碼,但我居然錯過了空間行之間。

<Text> 
    <Text style={{color: '#fff', fontWeight: '600', fontSize: 26, backgroundColor: 'blue' }}> 
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    </Text> 
</Text> 
+0

我無法嚴格按照樣式設置文本重新創建所需的行爲。我認爲你必須有創意才能完成這項工作,而且我不太確定這些選項的可靠程度。如果使用固定類型的字體,則可以計算換行符並將它們分解爲單獨的組件。或者,如果您可以計算文本將要佔用的行數,則可以將絕對定位的空白視圖與白色背景進行比較以模擬效果。我認爲這些都不是很好的解決方案,但也許我可能會給你一些想法。 –

+0

它實際上很容易重現OP的預期結果與幾種不同的解決方案可用... – Maxwelll

+0

@webdevil你設法解決這個問題? –

回答

1

在造型使用lineHeight應該做你要找的內容:

<Text> 
<Text style={{color: '#fff', fontWeight: '600', fontSize: 26, backgroundColor: 'blue', lineHeight: 20 }}> 
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
</Text> 

+0

謝謝Matt,我已經試過你的代碼,但它只是放大了行間的「填充」,但它們仍然連接在一起。 – WebDevil

1

我是能夠實現使用類似於特拉維斯白以上建議解決這個效果。 Image of effect in action

這絕不是一個完美的解決方案,而我幾乎可以肯定有,我不處理的使用情況,但在這裏它是:

class HighlightText extends Component { 
    state = { lines: [] }; 

    renderLines() { 
     let textString = this.props.children; 
     // splitOn is integer value. Enter expected max char count per line as prop 
     const splitOn = this.props.splitOn; 
     // Adds space to end of string, preventing cutoff of last word 
     const singleSpace = ' '; 
     textString = textString.concat(singleSpace); 
     const numOfLines = Math.ceil(textString.length/splitOn); 
     let lineStart = 0; 
     let lineEnd = textString.slice(0, splitOn).lastIndexOf(' '); 
     let fakeLineEnd = lineStart + splitOn; 
     /* multiplying x2 to handle for awkward splits before very long words 
     that can push content beyond the above calculated numOfLines */ 
     for (i = 0; i < numOfLines * 2; i++) { 
      let line = textString.slice(lineStart, lineEnd); 
      // Adds spaces to start and end of already populated lines for visual padding 
      if (line.length > 0) { 
       line = singleSpace + line + singleSpace; 
       this.state.lines.push(line); 
      } 
      lineStart = lineEnd + 1; 
      fakeLineEnd = lineStart + splitOn; 
      lineEnd = textString.slice(0, fakeLineEnd).lastIndexOf(' '); 
     } 
     return this.state.lines.map((line, i) => 
      <View 
       style={{ 
        marginTop: this.props.marginTop, 
      }} 
      > 
       <Text> 
        <Text 
         style={{ 
          fontSize: this.props.fontSize, 
          color: this.props.color, 
          backgroundColor: this.props.backgroundColor 
         }} 
         key={i.toString()} 
        > 
          {line} 
         </Text> 
       </Text> 
      </View> 
     ); 
    } 

    render() { 
     return (
      <View> 
       {this.renderLines()} 
      </View> 
     ); 
    } 
} 

編輯補充:我 還應該提到我得到以下非重大錯誤。

「數組或迭代器中的每個孩子都應該有一個唯一的」鍵「支柱。」

所以,要知道,如果你選擇實現這一點。

相關問題