【问题标题】:Style Inheritance of React NativeReact Native 的风格继承
【发布时间】:2020-01-17 15:44:11
【问题描述】:

假设我们有这样的<View>

<View>
    <Text h4 style={{color: theme.colors.success}}>Heading</Text>
    <Text>Normal text</Text>
    <Text style={{color: theme.colors.warning}}>Warning text</Text>
</View>

我需要&lt;View&gt; 的每个孩子都位于该视图的中心。

我尝试将style={{textAlign: 'center'}} 添加到父&lt;View&gt;,但它不起作用。

如何做到不手动给每个子组件添加style={{textAlign: 'center'}}

【问题讨论】:

  • 你在View中试过alignItemsjustifyContent吗?

标签: reactjs react-native styles


【解决方案1】:

垂直居中元素。

<View style={{flex:1,justifyContent:'center'}}>
  ...
</View>

水平居中元素。

<View style={{flex:1,alignItems:'center'}}>
  ...
</View>

在水平和垂直方向居中。

<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
  ...
</View>

我加了flex:1来拉伸屏幕,你也可以设置固定width,height

请注意,在 React Native 中,所有元素默认按列排列。这与 web 相反。

【讨论】:

    【解决方案2】:

    试试这个

    <View style = {{flex : 1, justifyContent : 'center',alignContent : 'center', alignItems:'center'}}>
        <Text h4 style={{color: theme.colors.success}}>Heading</Text>
        <Text>Normal text</Text>
        <Text style={{color: theme.colors.warning}}>Warning text</Text>
    </View>
    

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 2013-04-30
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多