React-Native中通用组件(Alert、Loading)

移动端开发过程中Alert和Loading框是必不可少的组件,各个平台都有提供相应的API,当然UI样式、响应方式具有平台的差异,React-Native(iOS、Android)项目中使用一套代码,想要抹平平台差异就需要自己单独实现一套。
最近的项目中有做相关方面的工作,特意从项目中抽离相关代码逻辑,封装成独立组件,这里做一下简单的介绍。

react-native-overlayer

react-native项目中通用的浮层组件
源码: https://github.com/yongqianvip/react-native-overlayer

功能

  • 通用RRCAlert组件
  • 通用RRCLoading组件

install

npm i react-native-overlayer --save

RRCAlert

  • 引用

      import { RRCAlert } from 'react-native-overlayer';
      ...
      RRCAlert.alert(title, content, buttons, callback, options);
    
  • options

    key default value desc
    contentTextStyle null 弹框content的文本样式
  • 当 buttons.length > 2 时,弹窗中的按钮按纵向排列

RRCLoading

  • 引用

      import { RRCLoading } from 'react-native-overlayer';
      import LoadingImage from './src/loading.gif';
      ...
      const options = { loadingImage: LoadingImage, text: 'gogogo' };
      RRCLoading.setLoadingOptions(options);
    
      RRCLoading.show();
    
      RRCLoading.hide();
    
  • options

    key default value desc
    loadingImage null 图片(gif)
    text 加载中... loading框中显示的文本
  • 在android中使用gif图需要添加额外配置,在android/app/build.gradle中添加如下代码

      dependencies {
        // 如果你需要支持GIF动图
        compile 'com.facebook.fresco:animated-gif:1.3.0'
      }
    

Alert和Loading同时出现

场景 效果
多次RRCAlert.alert() 优先展示最后一个(倒序展示)
多次RRCLoading.show() 仅展示最后一个,RRCLoading.hide()时移除
当loading未消失时触发RRCAlert.alert() 优先显示loading,loading消失后显示alert
当alert未消失时触发RRCLoading.show() 优先显示loading,loading消失后显示alert

效果

React-Native中通用组件(Alert、Loading)_第1张图片
alert&&loading.gif

核心实现

这个组件参照teaset的overlay来实现的,主要思路是在RN组件的最外层包了一层View(RRCTopView),本组件即是加载在RRCTopView中的视图,使用绝对布局(position: 'absolute'), 其核心的代码如下:

if (!AppRegistry.registerComponentOld) {
  AppRegistry.registerComponentOld = AppRegistry.registerComponent;
}

AppRegistry.registerComponent = function (appKey, componentProvider) {

  class RootElement extends Component {
    render() {
      let Component = componentProvider();
      return (
        
          
        
      );
    }
  }

  return AppRegistry.registerComponentOld(appKey, () => RootElement);
}

你可能感兴趣的:(React-Native中通用组件(Alert、Loading))