【问题标题】:React-native: position elements in the center and flex-endReact-native:将元素定位在中心和 flex-end
【发布时间】:2021-08-05 19:14:34
【问题描述】:

是否可以有如下布局(不诉诸绝对定位)?

|...........centreElement.......RightElement|

好像 justifyContent 是 'space-between' 但没有第一个元素。我也想过 'justifyContent: 'centre'' 然后在 RightElement 上尝试 'justifySelf: 'flex-end' 但这个属性不存在。

<View styles={styles.container}>
  <Text>centreElement</Text>
  <Text>RightElement</Text>
</View>

container: {
    flexDirection: 'row',
    justifyContent: 'center'
}

【问题讨论】:

    标签: react-native flexbox


    【解决方案1】:

    您的代码有错误,请将代码从&lt;View styles={styles.container}&gt;更新为&lt;View style={styles.container}&gt;

    请尝试以下代码:

    <View style={styles.container}>
         <View style={{ flex: 1 }} />
         <View style={{ flex: 1 }}>
            <Text>centreElement</Text>
         </View>
         <View style={{ flex: 1 }}>
            <Text>RightElement</Text>
         </View>
    </View>
    

    【讨论】:

      【解决方案2】:

      使用绝对的理想解决方案。 CentreElement 文本可能不在中心,但如果没有 absolute,您也无法对齐它,因为您没有让内容占用 100% 宽度,这是将内容正确对齐到中心所需的宽度。以下步骤可以为您带来满意的结果:

      • 只需将flexDirection: 'row' 发送给容器
      • 同时提供文本 CentreElementRightElement 50% width
      • 将它们都对齐到right,然后完成!!

      代码:

      export default function App() {
        return (
          <View style={styles.container}>
            {/* Txt container*/}
            <View style={styles.textContainer}>
              <Text style={styles.text}>
                CentreElement
              </Text>
              <Text style={styles.text}>
                RightElement
              </Text>
            </View>
          </View>
        );
      }
      
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          justifyContent: 'center',
          paddingTop: Constants.statusBarHeight,
          backgroundColor: '#ecf0f1',
          padding: 8,
        },
        textContainer: {
          width: '100%',
          flexDirection: 'row'
        },
        text: {
          textAlign: 'right', 
          width: '50%', 
          fontSize: 16, 
          fontWeight: 'bold'
        }
      });
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 2021-01-07
        • 2020-03-21
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-19
        相关资源
        最近更新 更多