您现在的位置是:网站首页> 编程资料编程资料
React Native Modal 的封装与使用实例详解_React_
2023-05-24
1046人已围观
简介 React Native Modal 的封装与使用实例详解_React_
背景
在使用 React Native(以下简称 RN ,使用版本为 0.59.5) 开发 App 的过程中,有许许多多使用到弹窗控件的场景,虽然 RN 自带了一个 Modal 控件,但是在使用过程中它有一些不太好的体验和问题。
- Android 端的 Modal 控件无法全屏,也就是内容无法从状态栏处开始布局。
- ios 端的 Modal 控件的层级太高,是基于 window 的,如果在 Modal 中打开一个新的 ViewController 界面的时候,将会被 Modal 控件给覆盖住,同时 ios 的 Modal 控件只能弹出一个。
针对上面所发现的问题,我们需要对 RN 的 Modal 控件整体做一个修改和封装,以便于在使用中可以应对各种不同样的业务场景。
Android FullScreenModal 的封装使用
针对第一个问题,查看了 RN Modal 组件在 Android 端的实现,发现它是对 Android Dialog 组件的一个封装调用,那么假如我能实现一个全屏展示的 Dialog,那么是不是在 RN 上也就可以实现全屏弹窗了。
Android 原生实现全屏 Dialog
FullScreenDialog 主要实现代码如下
public class FullScreenDialog extends Dialog { private boolean isDarkMode; private View rootView; public void setDarkMode(boolean isDarkMode) { this.isDarkMode = isDarkMode; } public FullScreenDialog(@NonNull Context context, @StyleRes int themeResId) { super(context, themeResId); } @Override public void setContentView(@NonNull View view) { super.setContentView(view); this.rootView = view; } @Override public void show() { super.show(); StatusBarUtil.setTransparent(getWindow()); if (isDarkMode) { StatusBarUtil.setDarkMode(getWindow()); } else { StatusBarUtil.setLightMode(getWindow()); } AndroidBug5497Workaround.assistView(rootView, getWindow()); } }在这里主要起作用的是 StatusBarUtil.setTransparent(getWindow()); 方法,它的主要作用是将状态栏背景透明,并且让布局内容可以从 Android 状态栏开始。
/** * 使状态栏透明,并且是从状态栏处开始布局 */ @TargetApi(Build.VERSION_CODES.KITKAT) private static void transparentStatusBar(Window window) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { View decorView = window.getDecorView(); int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; decorView.setSystemUiVisibility(option); window.setStatusBarColor(Color.TRANSPARENT); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } }这里需要注意的是,该方法只有在 Android 4.4 以上才会有效果,不过如今已经是 9012 年了,主流 Android 用户使用的版本应该没有低于 Android 4.4 了吧。
封装给 RN 进行相关的调用
Android 原生部分实现
有了 FullScreenDialog ,下一步就是封装组件给 RN 进行调用了,这里主要的步骤就是参考 RN Modal 的 Android 端实现,然后替换其中的 Dialog 为 FullScreenDialog,最后封装给 RN 进行调用。
public class FullScreenModalManager extends ViewGroupManager{ @Override public String getName() { return "RCTFullScreenModalHostView"; } public enum Events { ON_SHOW("onFullScreenShow"), ON_REQUEST_CLOSE("onFullScreenRequstClose"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } @Override @Nullable public Map getExportedCustomDirectEventTypeConstants() { MapBuilder.Builder builder = MapBuilder.builder(); for (Events event : Events.values()) { builder.put(event.toString(), MapBuilder.of("registrationName", event.toString())); } return builder.build(); } @Override protected FullScreenModalView createViewInstance(ThemedReactContext reactContext) { final FullScreenModalView view = new FullScreenModalView(reactContext); final RCTEventEmitter mEventEmitter = reactContext.getJSModule(RCTEventEmitter.class); view.setOnRequestCloseListener(new FullScreenModalView.OnRequestCloseListener() { @Override public void onRequestClose(DialogInterface dialog) { mEventEmitter.receiveEvent(view.getId(), Events.ON_REQUEST_CLOSE.toString(), null); } }); view.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { mEventEmitter.receiveEvent(view.getId(), Events.ON_SHOW.toString(), null); } }); return view; } @Override public LayoutShadowNode createShadowNodeInstance() { return new FullScreenModalHostShadowNode(); } @Override public Class extends LayoutShadowNode> getShadowNodeClass() { return FullScreenModalHostShadowNode.class; } @Override public void onDropViewInstance(FullScreenModalView view) { super.onDropViewInstance(view); view.onDropInstance(); } @ReactProp(name = "autoKeyboard") public void setAutoKeyboard(FullScreenModalView view, boolean autoKeyboard) { view.setAutoKeyboard(autoKeyboard); } @ReactProp(name = "isDarkMode") public void setDarkMode(FullScreenModalView view, boolean isDarkMode) { view.setDarkMode(isDarkMode); } @ReactProp(name = "animationType") public void setAnimationType(FullScreenModalView view, String animationType) { view.setAnimationType(animationType); } @ReactProp(name = "transparent") public void setTransparent(FullScreenModalView view, boolean transparent) { view.setTransparent(transparent); } @ReactProp(name = "hardwareAccelerated") public void setHardwareAccelerated(FullScreenModalView view, boolean hardwareAccelerated) { view.setHardwareAccelerated(hardwareAccelerated); } @Override protected void onAfterUpdateTransaction(FullScreenModalView view) { super.onAfterUpdateTransaction(view); view.showOrUpdate(); } }
在这里有几点需要注意的
- 由于 RN Modal 已经存在了 onShow 和 onRequestClose 回调,这里不能再使用这两个命名,所以这里改成了 onFullScreenShow 和 onFullScreenRequstClose,但是在 js 端还是重新命名成 onShow 和 onRequestClose ,所以在使用过程中还是没有任何变化
- 增加了 isDarkMode 属性,对应上面的状态栏字体的颜色
- 增加了 autoKeyboard 属性,根据该属性判断是否需要自动弹起软件盘
其他的一些属性和用法也就跟 RN Modal 的一样了。
JS 部分实现
在 JS 部分,我们只需要 Android 的实现就好了,ios 还是沿用原来的 Modal 控件。这里参照 RN Modal 的 JS 端实现如下
import React, {Component} from "react"; import {requireNativeComponent, View} from "react-native"; const FullScreenModal = requireNativeComponent('RCTFullScreenModalHostView', FullScreenModalView) export default class FullScreenModalView extends Component { _shouldSetResponder = () => { return true; } render() { if (this.props.visible === false) { return null; } const containerStyles = { backgroundColor: this.props.transparent ? 'transparent' : 'white', }; return ( this.props.onShow && this.props.onShow()} onFullScreenRequstClose={() => this.props.onRequestClose && this.props.onRequestClose()}> {this.props.children} ) } } 使用 RootSiblings 封装 Modal
针对第二个问题,一种方法是通过 ios 原生去封装实现一个 Modal 控件,但是在 RN 的开发过程中,发现了一个第三方库 react-native-root-siblings , 它重写了系统的 AppRegistry.registerComponent 方法,当我们通过这个方法注册根组件的时候,替换根组件为我们自己的实现的包装类。包装类中监听了目标通知 siblings.update,接收到通知就将通知传入的组件视图添加到包装类顶层,然后进行刷新显示。通过 RootSiblings 也可以实现一个 Modal 组件,而且它的层级是在当前界面的最上层的。
实现界面 Render 相关
由于 RootSiblings 的实现是通过将组件添加到它注册到根节点中的,并不直接通过 Component 的 Render 进行布局,而 RN Modal 的显示隐藏是通过 visible 属性进行控制,所以在 componentWillReceiveProps(nextProps) 中根据 visible 进行相关的控制,部分实现代码如下
render() { if (this.props.visible) { this.RootSiblings && this.RootSiblings.update(this.renderRootSiblings()); } return null; } componentWillReceiveProps(nextProps) { const { onShow, animationType, onDismiss } = this.props; const { visible } = nextProps; if (!this.RootSiblings && visible === true) { // 表示从没有到要显示了 this.RootSiblings = new RootSiblings(this.renderRootSiblings(), () => { if (animationType === 'fade') { this._animationFadeIn(onShow); } else if (animationType === 'slide') { this._animationSlideIn(onShow); } else { this._animationNoneIn(onShow); } }); } else if (this.RootSiblings && visible === false) { // 表示显示之后要隐藏了 if (animationType === 'fade') { this._animationFadeOut(onDismiss); } else if (animationType === 'slide') { this._animationSlideOut(onDismiss); } else { this._animationNoneOut(onDismiss); } } }实现 Modal 展示动画相关
RN Modal 实现了三种动画模式,所以这里在通过 RootSiblings 实现 Modal 组件的时候也实现了这三种动画模式,这里借助的是 RN 提供的 Animated 和 Easing 进行相关的实现
- ‘none’ 这种不必多说,直接进行展示,没有动画效果
- ‘fade’ 淡入浅出动画,也就是透明度的一个变化,这里使用了 Easing.in 插值器使得效果更加平滑
- ‘slide’ 幻灯片的滑入画出动画,这是是组件 Y 方向位置的一个变化,这里使用了 Easing.in 插值器使得效果更加平滑
完整的一个 使用 RootSiblings 封装 Modal 实现代码如下
import React, { Component } from 'react'; import { Animated, Easing, Dimensions, StyleSheet, } from 'react-native'; import RootSiblings from 'react-native-root-siblings'; const { height } = Dimensions.get('window'); const animationShortTime = 250; // 动画时长为250ms export default class ModalView extends Component { constructor(props) { super(props); this.state = { a
相关内容
- vue常用组件之confirm用法及说明_vue.js_
- react使用useImperativeHandle示例详解_React_
- vue-router路由跳转问题 replace_vue.js_
- vue实现导出word文档功能实例(含多张图片)_vue.js_
- 在vue中如何引入外部less文件_vue.js_
- vue-router如何实时动态替换路由参数(地址栏参数)_vue.js_
- element-ui中el-input只输入数字(包括整数和小数)_vue.js_
- Vue Router修改query参数url参数没有变化问题及解决_vue.js_
- vue中如何防止用户频繁点击按钮详解_vue.js_
- vue中的路由传值与重调本路由改变参数_vue.js_
点击排行
本栏推荐
