您的当前位置:首页正文

ScrollView 源码解析

2024-11-11 来源:个人技术集锦

ScrollView 源码解析

//scrollview.png

我似乎看到了 RecycleView 身影。

由于 ScrollView 的源码比较长,而且比较复杂,所以这里就不把完整的代码贴出来了,这里先把关注点放在 render() 函数里面,render里面 return 语句如下:

if (refreshControl) {
  if (Platform.OS === 'ios') {
    // On iOS the RefreshControl is a child of the ScrollView.
    return (
      <ScrollViewClass {...props} ref={this._setScrollViewRef}>
        {refreshControl}
        {contentContainer}
      </ScrollViewClass>
    );
  } else if (Platform.OS === 'android') {
    // On Android wrap the ScrollView with a AndroidSwipeRefreshLayout.
    // Since the ScrollView is wrapped add the style props to the
    // AndroidSwipeRefreshLayout and use flex: 1 for the ScrollView.
    return React.cloneElement(
      refreshControl,
      {style: props.style},
      <ScrollViewClass {...props} style={baseStyle} ref={this._setScrollViewRef}>
        {contentContainer}
      </ScrollViewClass>
    );
  }
}
return (
  <ScrollViewClass {...props} ref={this._setScrollViewRef}>
    {contentContainer}
  </ScrollViewClass>
);

第一行 if 语句里面根据是否为 ScrollView 指定了 RefreshControl 刷新控件,如果有则会生成,如果没有设置,则生成的控件只包含 contentContainer。这里出现了我们不熟悉的 Component ScrollViewClass,其实这个是 ScrollView 的具体实现类。我们往上翻一翻就可以看到这个 ScrollViewClass 的身影:

let ScrollViewClass;
if (Platform.OS === 'ios') {
  ScrollViewClass = RCTScrollView;
} else if (Platform.OS === 'android') {
  if (this.props.horizontal) {
    ScrollViewClass = AndroidHorizontalScrollView;
  } else {
    ScrollViewClass = AndroidScrollView;
  }
}

上面的代码根据不同的操作系统平台,分别将不同的 Component 赋予 ScrollViewClass 变量,这里可以看到,ios 用的是 RCTScrollView这个类,android 上根据 主轴(horizontal属性 true或者false)方向是水平或者垂直,来使用不同的两个 Component 控件,具体的实现类是由下面的代码决定的(这里只展示一种)

  AndroidScrollView = requireNativeComponent('RCTScrollView', ScrollView, nativeOnlyProps);

RCTScrollView 是原生 android 代码封装了 原生 ScrollView 控件的一个组件类,能在react natives android 相关源码上看到相关的实现(由于这里将某个组件类注册为RCTScrollView,在 android 上具体的类名不一定是这个,实际上其对应的类名是 ReactScrollView)我们这里暂且不管,总之需要知道,RCTScrollView 对应的是一个封装的好的android 原生 ScrollView 就好了,我们回到之前的代码。看下这行代码:

  <ScrollViewClass {...props} ref={this._setScrollViewRef}> //这里标签未闭合只是为了说明语法

这里将 ScrollView 的属性,通过 jsx 语法 “…props”全部传递到 ScrollViewClass 里面去了,然后通过 ref 指向自己。接着我们看到这样两行代码:

        {refreshControl}
        {contentContainer}

在 React 的语法中,碰到{}就解析为 javascript 表达式,所以这里两个 javascript 表达式,前者是生成了 refreshControl 下拉刷新控件,后者是 contentContainer 表示的是一个 ScrollView Item 的内容,具体可看下面的代码:

// 定义了一个 const 常量,不可变常量(ES6语法),把一个 View 赋值给了这个常量
const contentContainer =
  <View
    {...contentSizeChangeProps}
    ref={this._setInnerViewRef}
    style={contentContainerStyle}
    removeClippedSubviews={this.props.removeClippedSubviews}
    collapsable={false}>
    {this.props.children}
  </View>;
源码路径 com.facebook.react.views.scroll.ReactScrollView 
显示全文