【问题标题】:How can I set margin for Components using FlexBox?如何使用 FlexBox 为组件设置边距?
【发布时间】:2019-07-10 09:44:22
【问题描述】:

我一直在通过使用我需要的 flex 创建空视图组件来设置 flexbox 的边距,但我想知道是否有一种方法可以更优雅地做到这一点。这是我一直在做的事情:

const MyComponent = () => (
  <View style={{ flex: 1, justifyContent: 'space-around', alignItems: 'center'}}>
    <View style={{ flex: 1 }} />
    <View style={{ flex: 1 }}>
      <Text>My real content here</Text>
    </View>
  </View>
);

请注意,我只是放置了第一个内部视图以提供我想要的适当边距。有没有一种优雅(又名正确)的方式来做到这一点?

【问题讨论】:

    标签: javascript css react-native


    【解决方案1】:

    您可以通过将您的flexbox 内容包装在元素内并将边距应用于此element 来进行包装,就像这样的html 和css:

    *{
      margin:0;
    }
    .row-flex{
    display:flex;
    flex-wrap:wrap;
    width:100vw
    }
    .col{
    width:calc(100%/3);
     height:200px;
        margin-top:20px;
    }
    .content{
    background-color:green;
      width:90%;
      margin:0 auto;
      height:100%;
    }
    <div class="row-flex">
    <div class="col">
    <div class="content"></div>
      </div>
    <div class="col">
    <div class="content"></div></div>
    <div class="col">
    <div class="content"></div></div>
    <div class="col">
    <div class="content"></div></div>
    <div class="col">
    <div class="content"></div></div>
    </div>
    </div>

    【讨论】:

      【解决方案2】:

      不知道为什么你真的需要一个内部视图来设置边距。您可以将边距赋予 Textcomponent 的父视图。

      你能分享截图,也许我可以更好地指导你?

      const MyComponent = () => (
        <View style={{ flex: 1, justifyContent: 'space-around', alignItems: 'center'}}>
          <View style={{ flex: 1, margin: 20 }}>
            <Text>My real content here</Text>
          </View>
        </View>
      );
      

      【讨论】:

      • 我不是在寻找一个硬编码的边距,而是一个响应/灵活的边距,与我的内容大小相同
      • 好的,你可以使用百分比。例如保证金:'1%'
      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多