【问题标题】:React Native Flex Box: alignSelf of child component does not respect Justify Content of ParentReact Native Flex Box:子组件的alignSelf不尊重Parent的Justify Content
【发布时间】:2020-08-17 11:46:02
【问题描述】:

在反应本机登录按钮中,我试图将图标水平向左和垂直放置在中心,并将文本水平和垂直放置在中心。使用下面的代码,只要我将 alignSelf 作为图标上的“中心”,它就会失去其垂直位置。根据文档 alignSelf 应该只覆盖横轴而不是主轴中的属性。这里的图标是 SVG 图标。

    const GoogleSignInBtn = ({style, onPress, children}) => {
      const {buttonStyles, textStyle, iconStyle} = styles;
      return (
        <TouchableOpacity onPress={onPress} style={buttonStyles}>
         <GoogleIcon style={iconStyle} />
         <Text style={textStyle}>{children}</Text>
        </TouchableOpacity>
      );
   };
    const styles = {
      textStyle: {
      color: '#007aff',
      fontSize: 16,
      fontWeight: '600',
      paddingTop: 10,
      paddingBottom: 10,
    },
    buttonStyles: {
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: 5,
      flex: 1,
      borderRadius: 5,
      borderWidth: 1,
      borderColor: '#007aff',
      marginLeft: 5,
      marginRight: 5,
    },
      iconStyle: {
      height: 20,
      width: 20,
      alignSelf: 'flex-start',
    },
  [Screen Shot of output][1]};

【问题讨论】:

    标签: react-native flexbox


    【解决方案1】:

    试试

    const styles = StyleSheet.create({
          textStyle: {
          color: '#007aff',
          fontSize: 16,
          fontWeight: '600',
          paddingTop: 10,
          paddingBottom: 10,
          marginHorizontal: 'auto',
        },
        buttonStyles: {
          justifyContent: 'flex-start',
          alignItems: 'center',
          marginTop: 5,
          flex: 1,
          flexDirection: 'row',
          borderRadius: 5,
          borderWidth: 1,
          borderColor: '#007aff',
          marginLeft: 5,
          marginRight: 5,
        },
          iconStyle: {
          height: 20,
          width: 20,
          alignSelf: 'center',
        },
    });
    

    您确实覆盖了alignItems,但是无论出于何种原因,您的flexDirection 似乎被隐式设置为'column',因此该图标被设置在弹性框的顶部。

    flexDirection 更改为'row' 允许项目水平定向,因此alignSelf 可以按需要工作。

    此外,我使用marginHoritonal: auto 将文本居中。 有关这方面的更多信息,请参阅In CSS Flexbox, why are there no “justify-items” and “justify-self” properties?

    【讨论】:

    • 您好,谢谢,文本卡在左边而不是中间,父容器设置为 justifyContent: 'flex-start',alignItems: 'center',标志将水平向左和已经垂直居中,因此应用 align self ,由于 flexDirection: 'row', (cross axis) 现在在垂直方向上有效,不会产生任何差异。如果我错了,请纠正我。
    • 这是正确的,alignSelf: 'center' 在这种情况下将不起作用,我不确定您的 children 有什么问题,我不知道对象是什么所以我使用了一些普通的代替文字。 Here's my snack you can test with
    • 您好,谢谢,Children 只是作为 prop.children 传递的纯文本,代码对您有用吗?我用的是vanilla react native,想知道有没有其他地方的副作用
    猜你喜欢
    • 2021-06-11
    • 2018-07-03
    • 2016-02-07
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    相关资源
    最近更新 更多