React Native - StyleSheet.absoluteFill()和StyleSheet.absoluteFillObject()有什么区别?

23

这份文档提供了一个使用StyleSheet.absoluteFillObject()的例子,与StyleSheet.absoluteFill()的行为相同:

const styles = StyleSheet.create({
  wrapper: {
    ...StyleSheet.absoluteFillObject,
    top: 10,
    backgroundColor: 'transparent',
  },
});

StyleSheet.absoluteFill()StyleSheet.absoluteFillObject()有什么区别?能否举个简单的例子说明一下,谢谢!

7个回答

28

absoluteFill 是一种简单的方式,可以将视图设置为全屏和绝对定位。它是以下代码的快捷方式:

{
 position: 'absolute',
 top: 0,
 left: 0,
 bottom: 0,
 right: 0

}

可以像这样使用它来扩展您的其他样式:

const styles = StyleSheet.create({
  container: {
   backgroundColor: 'red'
   }
});
<View style={[StyleSheet.absoluteFill, styles.container]} />

absoluteFillObject 如果你想要绝对定位你的视图,但需要将它向下偏移20像素以抵消状态栏(例如)。 你可以将StyleSheet.absoluteFillObject展开到你的样式中,然后覆盖其中的一个值。

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
   top: 20,
    backgroundColor: 'red'
  }
});
<View style={styles.container} />

12
你在回答StyleSheet.absoluteFillObject时提到的那件事也可以用StyleSheet.absoluteFill来做,那么这两者有什么区别? - Purple Bytes
1
根据这个答案 https://dev59.com/VlQJ5IYBdhLWcg3wg2T4#69968270,当使用TypeScript时会有所不同,因为你不能将`StyleSheet.absoluteFill`展开到样式表中。 - Can Rau

15

这两者之间没有区别。你可以在StyleSheet.js中看到:

 /**
   * A very common pattern is to create overlays with position absolute and zero positioning,
   * so `absoluteFill` can be used for convenience and to reduce duplication of these repeated
   * styles.
   */
  absoluteFill: (absoluteFill: any), // TODO: This should be updated after we fix downstream Flow sites.

  /**
   * Sometimes you may want `absoluteFill` but with a couple tweaks - `absoluteFillObject` can be
   * used to create a customized entry in a `StyleSheet`, e.g.:
   *
   *   const styles = StyleSheet.create({
   *     wrapper: {
   *       ...StyleSheet.absoluteFillObject,
   *       top: 10,
   *       backgroundColor: 'transparent',
   *     },
   *   });
   */
  absoluteFillObject: absoluteFill,

enter image description here


6
没问题,"Use the Source, Luke"!这里是查询最新版本情况的参考链接: https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/StyleSheet.js#L266 - iqqmuT

7

我可能迟到了一些,但typescript中的absoluteFillabsoluteFillObject有一些区别。

主要区别在于typescript中:

  • absoluteFill 的类型为 RegisteredStyle<StyleSheet.AbsoluteFillStyle>
  • absoluteFillObject 的类型为 StyleSheet.AbsoluteFillStyle
const styles = StyleSheet.create({
    container: {
        // must use "absoluteFillObject" in typescript
        ...StyleSheet.absoluteFillObject,
    }
})

JavaScript 没有区别。

4
从版本0.62开始,根据官方文档,两者没有任何区别。
如果您像我一样使用EXPO Snack,则目前在Web上预览absoluteFill似乎存在问题。在实际设备上应该没问题。


2

在当前(React Native 0.66)版本中,文档指出:

使用 absoluteFillabsoluteFillObject 没有区别。


1
我尝试打印出absoluteFillabsoluteFillObject的值。
它们没有区别。它们的值相同。
[LOG] absoluteFill: {"bottom": 0, "left": 0, "position": "absolute", "right": 0, "top": 0}
[LOG] absoluteFillObject: {"bottom": 0, "left": 0, "position": "absolute", "right": 0, "top": 0}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接