首页 > 解决方案 > Flex 在 facebook.io 和实际应用程序中的工作方式不同,React Native

问题描述

我试图让ScrollView孩子的大小与 scrollView 本身一样。代码非常简单:

  <View style={{ flex: 1 }}>
    <ScrollView style={[{ flex: 1, backgroundColor: 'green' }]}>
      <View style={{ flex: 1, backgroundColor: 'red' }}>
      </View>
    </ScrollView>
  </View>

问题是在模拟器上本地我得到绿屏(元素检查器中甚至没有显示子视图)。

facebook 教程上,结果是不同的:

在此处输入图像描述

为什么它的工作方式不同?

标签: react-native

解决方案


您遇到的差异实际上是React Native Web(官方 React Native 文档在其示例中使用)与 React Native 之间的差异。

鉴于 React Native Web 不直接依赖 React Native 作为依赖项这一事实,这种不一致很可能是由于<ScrollView>组件的不同实现以及样式道具的处理和/或传播方式。

一般来说,如果官方文档中提供的示例也有显示结果的设备,我不会认为它们是理所当然的,因为这些示例很可能是为在 React Native Web 上工作而定制的,可能会也可能不会(就像在这个case) 表现得像 React Native。

细节

React Native<ScrollView>实际上将子视图包装成 a <ScrollContentContainerViewClass>,因此需要区分滚动视图本身的样式(通常的style道具)和此包装器的样式(@yangguang1029 的答案contentContainerStyle中提到的:

// in render function of ScrollView class.
const contentContainer = (
  <ScrollContentContainerViewClass
    style={contentContainerStyle}> // styling for inner container view.
    {children}
  </ScrollContentContainerViewClass>
);

// other operations...

return (
  <ScrollViewClass {...props} ref={this._setScrollViewRef}> // here the "style" prop is propagated.
    {contentContainer}
  </ScrollViewClass>
);

来源:GitHub 上的 React Native ScrollView 源码


推荐阅读