Skip to content

Instantly share code, notes, and snippets.

@1uokun
Last active June 21, 2024 07:16
Show Gist options
  • Save 1uokun/1553994ef18ff6d51026c4a93e4c15ae to your computer and use it in GitHub Desktop.
Save 1uokun/1553994ef18ff6d51026c4a93e4c15ae to your computer and use it in GitHub Desktop.
react-native-root-view by AppRegistry.registerComponent
/**
* react-native-root-view
*
* @article https://www.jianshu.com/p/2c79684481b3
* @auth https://github.com/1uokun
* */
import React, { Component } from 'react';
import { StyleSheet, AppRegistry, View, ScrollView, DeviceEventEmitter } from 'react-native';
class RootView extends Component {
constructor(props) {
super(props);
this.state = {
toast: [],
};
}
render() {
return (
React.Children.count(this.state.toast) > 0 && <View style={StyleSheet.absoluteFill} pointerEvents="box-none">
{this.state.toast}
</View>
);
}
componentDidMount() {
DeviceEventEmitter.addListener('rootView_add', this.set, this);
DeviceEventEmitter.addListener('rootView_remove', this.remove, this);
}
componentWillUnmount(): void {
DeviceEventEmitter.removeListener('rootView_add', this.set);
DeviceEventEmitter.removeListener('rootView_remove', this.remove);
}
set = (view) => {
if (React.isValidElement(view)) {
this.setState({ toast: [view] });
}
};
remove = () => {
this.setState({ toast: [] });
};
}
AppRegistry.setWrapperComponentProvider(function() {
return function RootSiblingsWrapper(props) {
return (
<React.Fragment>
<ScrollView
contentContainerStyle={{ flex:1 }}
collapsable={false}
bounces={false}>
{props.children}
</ScrollView>
<RootView />
</React.Fragment>
);
};
});
export default {
set(view) {
DeviceEventEmitter.emit('rootView_add', view);
},
remove() {
DeviceEventEmitter.emit('rootView_remove');
},
};
@1uokun
Copy link
Author

1uokun commented Jun 21, 2024

Q: rootView will nest scroll, how to fix?

A: ScrollView wrapper children and set contentContainerStyle & collapsable & bounces prop like this ⬇️

AppRegistry.setWrapperComponentProvider(function() {
    return function RootSiblingsWrapper(props) {
        return (
        <React.Fragment>
-            {props.children}
+            <ScrollView
+               contentContainerStyle={{ flex:1 }}
+               collapsable={false}
+               bounces={false}>
+               {props.children}
+           </ScrollView>
            <RootView />
        </React.Fragment>
        );
    };
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment