【问题标题】:How to make a textAlign center in a paragraph如何在段落中使 textAlign 居中
【发布时间】:2019-09-13 06:52:26
【问题描述】:

我有一些这样的文本段落:

<Text>
    <Text>1111</Text>
    <Text>2222</Text>
    <Text style={{textAlign:"center"}}>
        <Text>3333</Text>
    </Text>
    <Text>4444</Text>
    <Text>5555</Text>
</Text>

显示如下:

11112222333344445555

虽然我希望它显示如下:

11112222
       3333
44445555

其中3333为textAlign Center

我该怎么做?

我尝试设置 flexDirection,但没有成功。


数据结构有点复杂,比如

{
    { text : 'aaaa'}
    { text: [
        {
            text: [
                { text: 'bbbb' },
                { text: 'cccc', style:'bold' },
                {
                    text : '3333',
                    style: 'center'
                },
                { text: 'dddd'},
            ], style: 'bold'
        },
        { text: 'eeee' }
    ]},
    { text: 'ffff', style:'i' },
    { text: 'gggg' }
}

由于View Component不能嵌套在Text Component中,所以无法将Text Wrapped 3333改为View。

【问题讨论】:

  • 你的预期输出是什么?
  • 3333 居中,而其他显示 textAlign:left

标签: react-native


【解决方案1】:

这对我有用

<View style={{ width: '100%', flexDirection: 'column' }}>
    <Text style={{ width: '100%' }}>1111</Text>
    <Text style={{ width: '100%' }}>2222</Text>
    <Text style={{ textAlign: "center", width: '100%' }}>
        <Text>3333</Text>
    </Text>
    <Text style={{ width: '100%' }}>4444</Text>
    <Text style={{ width: '100%' }}>5555</Text>
</View>

【讨论】:

    【解决方案2】:

    使用 View 组件作为容器,然后将您想要内联的项目包装在 Text 组件中。 example here

    编辑1:

    结构示例:

    <View>
      <text>
        <Text>1111</Text>
        <Text>2222</Text>
      </text>
      <Text style={{textAlign:"center"}}>
        <Text>3333</Text>
      </Text>
      <text>
        <Text>4444</Text>
        <Text>5555</Text>
      </text>
    </View>
    

    working example here

    【讨论】:

    • 但是可能需要居中的文本嵌套在另一个文本组件中。改成view会报错。
    • 你检查过这个例子吗?
    • 该示例有效,而文本组件直接位于视图组件中。但我正在尝试显示用户发布的段落。需要居中的文本可能嵌套在文本结构的深处,请参阅我在问题下方添加的示例。结构可能更复杂。
    • 根据documentation,您将需要使用 View 组件,否则您将无法完成该操作
    【解决方案3】:

    试试这个。

    <Text>
        <Text>1111</Text>
        <Text>2222</Text>
        <Text style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            <Text>3333</Text>
        </Text>
        <Text>4444</Text>
        <Text>5555</Text>
    </Text>
    

    【讨论】:

      【解决方案4】:

      您可以使用我在此处提到的 View。

        <View style={{alignItems:'flex-start'}}>
          <Text>111111</Text>
        </View>
        <View style={{alignItems:'center'}}>
        <Text>2222222</Text>
        </View>
        <View style={{alignItems:'flex-start'}}>
        <Text>333333</Text>
        </View>
      

      【讨论】:

      • 但是可能需要居中的文本嵌套在另一个文本组件中。改成view会报错。
      • 是的,为什么不呢?仅将嵌套的文本组件放在 View 中并更改其样式。
      • 这意味着我需要将所有父组件更改为 View,并将许多文本组件包装在另一个 Text 组件中。请参阅我在问题中添加的结构。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2021-06-10
      相关资源
      最近更新 更多