react-native彈窗封裝的方法
本文實例為大傢分享瞭react-native彈窗封裝的具體代碼,供大傢參考,具體內容如下
上圖
仿蘋果彈窗組件(android+ios均可用)
以上效果均基於本文的彈窗組件,後續將會介紹上面的組件,也可基於改組件定制更多組件
安裝依賴 yarn add react-native-root-siblings 或者 npm install react-native-root-siblings –save
主要代碼
顯示彈窗
export const showModal = (component) => { sibling = new RootSiblings(component); };
銷毀彈窗
export const destroySibling = (component) => sibling && sibling.destroy()
更新彈窗
export const update = (index, component) => sibling && sibling.update(<View>{component}</View>)
完整代碼
多彈窗管理不涉及,暫時介紹單個彈窗,感興趣的可以自己試試,將sibling改為數組;
//ShowModal.js import React from 'react'; import {View} from 'react-native'; import RootSiblings from 'react-native-root-siblings'; //全局彈框組件 let sibling = null; export const showModal = (component) => { sibling = new RootSiblings(component); }; export const destroySibling = (component) => sibling && sibling.destroy() export const update = (index, component) => sibling && sibling.update(<View>{component}</View>)
使用示例—>淡入背景
組件 ModalBg.js
import React from 'react'; import {Animated, InteractionManager, Easing, TouchableOpacity} from 'react-native'; import {getScreenHeight, getScreenWidth} from '../../utils/util'; import {destroyLastSibling} from '../showModal/ShowModal'; export default class ModalBg extends React.Component { animated = new Animated.Value(0); isShow = false; componentDidMount(): void { InteractionManager.runAfterInteractions(() => { this.handleAni(); }); } componentWillUnmount(): void { InteractionManager.runAfterInteractions(() => { this.handleAni(); }); } handleAni = () => { Animated.timing(this.animated, { toValue: this.isShow ? 0 : 1, duration: 250, easing: Easing.ease }).start(() => this.isShow = !this.isShow); }; render() { const opct = this.animated.interpolate({ inputRange: [0, 1], outputRange: [0, 0.4] }); return <Animated.View style={{ position: 'absolute', width: getScreenWidth(), height: getScreenHeight(), backgroundColor: '#000', opacity: opct, zIndex: 10 }}><TouchableOpacity onPress={() => { destroyLastSibling(); }} style={{flex: 1}} /></Animated.View>; } }
調用
showModal(<ModalBg />);
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- React Native Popup實現示例
- React Native項目中使用Lottie動畫的方法
- 用React Native制作一個簡單的遊戲引擎
- React中代碼分割的4種實現方式
- 可定制react18 input otp 一次性密碼輸入組件