2017-05-05 64 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> 
     ); 
    } 
} 

编辑补充:我 还应该提到我得到以下非重大错误。

“数组或迭代器中的每个孩子都应该有一个唯一的”键“支柱。”

所以,要知道,如果你选择实现这一点。

相关问题