移動(dòng)端開(kāi)發(fā)過(guò)程中Alert和Loading框是必不可少的組件,各個(gè)平臺(tái)都有提供相應(yīng)的API,當(dāng)然UI樣式、響應(yīng)方式具有平臺(tái)的差異,React-Native(iOS、Android)項(xiàng)目中使用一套代碼,想要抹平平臺(tái)差異就需要自己?jiǎn)为?dú)實(shí)現(xiàn)一套。
最近的項(xiàng)目中有做相關(guān)方面的工作,特意從項(xiàng)目中抽離相關(guān)代碼邏輯,封裝成獨(dú)立組件,這里做一下簡(jiǎn)單的介紹。
react-native-overlayer
react-native項(xiàng)目中通用的浮層組件
源碼: 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的文本樣式 當(dāng) buttons.length > 2 時(shí),彈窗中的按鈕按縱向排列
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動(dòng)圖 compile 'com.facebook.fresco:animated-gif:1.3.0' }
Alert和Loading同時(shí)出現(xiàn)
| 場(chǎng)景 | 效果 |
|---|---|
多次RRCAlert.alert()
|
優(yōu)先展示最后一個(gè)(倒序展示) |
多次RRCLoading.show()
|
僅展示最后一個(gè),RRCLoading.hide()時(shí)移除 |
當(dāng)loading未消失時(shí)觸發(fā)RRCAlert.alert()
|
優(yōu)先顯示loading,loading消失后顯示alert |
當(dāng)alert未消失時(shí)觸發(fā)RRCLoading.show()
|
優(yōu)先顯示loading,loading消失后顯示alert |
效果

alert&&loading.gif
核心實(shí)現(xiàn)
這個(gè)組件參照teaset的overlay來(lái)實(shí)現(xiàn)的,主要思路是在RN組件的最外層包了一層View(RRCTopView),本組件即是加載在RRCTopView中的視圖,使用絕對(duì)布局(position: 'absolute'), 其核心的代碼如下:
if (!AppRegistry.registerComponentOld) {
AppRegistry.registerComponentOld = AppRegistry.registerComponent;
}
AppRegistry.registerComponent = function (appKey, componentProvider) {
class RootElement extends Component {
render() {
let Component = componentProvider();
return (
<RRCTopView>
<Component {...this.props} />
</RRCTopView>
);
}
}
return AppRegistry.registerComponentOld(appKey, () => RootElement);
}