Last active
June 21, 2024 07:16
-
-
Save 1uokun/1553994ef18ff6d51026c4a93e4c15ae to your computer and use it in GitHub Desktop.
react-native-root-view by AppRegistry.registerComponent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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'); | |
}, | |
}; |
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
DO NOT USE
AppRegistry.registerComponent
This will cause the
props
carried duringNative
jump toReact-Native
to be lostFor example, NativeActivityA to ReactActivityB ,
intent. putExtra
something will be lostUSE
AppRegistry.setWrapperComponentProvider
✅