【问题标题】:What's the equivalent of React Native { flex: 1 } for React JS?React JS 的 React Native { flex: 1 } 的等价物是什么?
【发布时间】:2019-08-13 07:46:32
【问题描述】:

我在 React Native 中进行了很多编程,我正在尝试 React js(仅限 Web),但我不知道如何制作一个简单的 View,让所有屏幕都可以开始使用所有组件。

让我解释一下:

在 React Native 中,我使用 flex 处理视图尺寸,如下所示:

<View style={{ flex: 1 }}>
    <View style={{ flex: 0.5, backgroundColor: 'blue' }}>
      <Text>I'm a blue 50% screen View!</Text>
    </View>
    <View style={{ flex: 0.5, backgroundColor: 'yellow' }}>
      <Text>I'm a yellow 50% screen View!</Text>        
    </View>
</View>

但在 React JS 中,我必须使用无法识别 flex 的 div 标签。 我的意思是,我不能这样做:

<div style={{ flex: 1 }}>
    <div style={{ flex: 0.5, backgroundColor: 'blue' }}>
      <p>I'm a blue 50% screen View!</p>
    </div>
    <div style={{ flex: 0.5, backgroundColor: 'yellow' }}>
      <p>I'm a yellow 50% screen View!</p>        
    </div>
</div>

我必须如何在 React js 中为 div 使用这些样式来获得百分比结果?

【问题讨论】:

  • 什么意思,“我必须使用无法识别 flex 的 div 标签。” ?
  • 我的意思是我制作了一个样式为 flex 1 的 div 并且没有任何反应,而不是如果我在 react native 中做的话
  • 你仍然可以在你的CSS中使用div { flex: 1 }。这是flex-grow: 1;flex-shrink: 1; flex-basis: 0%; }的简写
  • 我做了,但没有任何反应,div 没有填满整个屏幕。

标签: javascript css reactjs react-native flexbox


【解决方案1】:

React Native 使用自己的 flexbox 实现 - https://facebook.github.io/react-native/docs/flexbox

在 React 中,您使用的是 CSS flexbox - https://developer.mozilla.org/en-US/docs/Glossary/Flexbox

Flexbox 在 React Native 中的工作方式与在 Web 上的 CSS 中的工作方式相同,但有一些例外。默认值不同,flexDirection默认为column而不是row,flex参数只支持单个数字。

在css中,还需要声明父容器为

.flex-container {
  display: flex;
}

这可能就是你所缺少的。

你的 flex 的纯 CSS 版本可能看起来像这样(样式为“字符串”版本):

<div style="display: flex; flex-direction: column; height: 100vh;">
    <div style="flex: 1; background-color: blue;">
      <p>I'm a blue 50% screen View!</p>
    </div>
    <div style="flex: 1; background-color: yellow;">
      <p>I'm a yellow 50% screen View!</p>        
    </div>
</div>

【讨论】:

  • 添加显示:flex;使 flexDirection 有效,但无法设置我的 div 获取所有屏幕,就像在反应原生中设置 flex: 1 一样
  • @MtgKhaJeskai codepen.io/anon/pen/jJXrLd这是你想要的吗?
  • 是的,类似的,但它不起作用。如果我用 flex: 1 创建一个 div,那么里面的另外 2 个 div 有 1 。 flex :0.2 和另一个 flex :0.8 应该意味着第一个是父 div 的 20%,另一个是 80%,但它不起作用。如果你是父 div,如果那个 div 有 flex: 1 它应该填满整个屏幕
  • 您还需要为 bodyhtmlelements 提供 100% 的高度。父母也需要有 100% 的高度
  • @MtgKhaJeskai 它的 0.2 总 flex 值 (0.2 + 0.8 = 1) => 0.2/1 = > parent div 高度的 20% - 所以如果你想全屏它 - 你的 parent div 需要 100% 的窗口高度
猜你喜欢
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 2019-03-29
  • 1970-01-01
相关资源
最近更新 更多