【问题标题】:React Native: Align Horizontally - Center and RightReact Native:水平对齐 - 中心和右侧
【发布时间】:2021-05-11 04:56:01
【问题描述】:

在我的 React Native 项目中,我需要对齐两个元素。一个应该在中心,另一个应该在屏幕的最右边。但是,我无法正确处理。

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.mainTitle}>
        <Text style={{display: 'flex'}}>
          Main Title
        </Text>
        <Text
        style={{
          color: '#528bb4',
          fontSize: 14,
          fontWeight:600,
          marginLeft: 'auto',
          width:10,
          display:'flex',
          marginRight:10
        }}
      >?</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  mainTitle: {    display: 'flex', flexDirection: 'row', backgroundColor: '#fff',height: '30%', width: '100%',alignItems: 'center',justifyContent: 'center',},
});

小吃网址:https://snack.expo.io/iXjlvlGpd

我无法将主要元素置于中心,而将下一个元素置于右侧。

【问题讨论】:

    标签: javascript css react-native


    【解决方案1】:

    您可以执行以下操作,为正确的文本设置绝对位置,并为文本设置 alignself 中心

      <View style={styles.mainTitle}>
        <Text style={{ display: 'flex', alignSelf: 'center' }}>Main Title</Text>
        <Text
          style={{
            color: '#528bb4',
            position: 'absolute',
            fontSize: 14,
            fontWeight: 600,
            right: 10,
            width: 10,
            display: 'flex',
            marginRight: 10,
          }}>
          ?
        </Text>
      </View>
    

    https://snack.expo.io/@guruparan/dfddf9

    【讨论】:

      【解决方案2】:

      这应该可以解决问题。

      1. 基本删除display: 'flex',因为它没有用。
      2. 接下来,当您提供 flex: 1 时,它会使 Text 元素占据其父元素中剩余的可用宽度。
      3. 现在元素采用全宽,给它textAlign: 'center' 以使文本显示在中心。

      <Text style={{ flex: 1, textAlign: 'center'}}>
         Main Title
      </Text>
      

      Here is the snack

      如果你想实现真正的中心,你需要使用绝对定位正确的元素,以便中心元素可以占据整个宽度。但是这种方法可能会导致重叠。

      【讨论】:

      • 谢谢。这真的很有帮助。是否有可能实现主标题的真正中心,使其实际上以整个宽度为中心,同时仍然使第二个元素右对齐?
      • 嘿。是的,如果我们在正确的元素上使用 position: 'absolute' 就可以实现真正的中心。更新了答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2011-03-01
      • 1970-01-01
      • 2012-09-12
      • 2020-09-08
      • 2018-06-23
      • 2015-09-02
      相关资源
      最近更新 更多