I already have a native Java app and I'm adding some new pages on react native. I'm trying to implement a method in java which will be called from the react-native component when the back button is pressed (both the device button and a button on the screen). Right now, the device back button is working perfectly, but the button on the screen is not! Here is what I have:
I have a Java class called SettingsPageModule
extending ReactContextBaseJavaModule
(I have already registered modules and packages as required), and this class has a method called exitSettingsPage
. This is the method I want to call from react.
In the react component, I have this:
import { BackHandler, NativeModules } from 'react-native';
import { Button } from "native-base";
var SettingsPageModule = NativeModules.SettingsPageModule;
export default class Settings extends Component {
constructor(props) {
super(props);
this.handleBackPress = this.handleBackPress.bind(this);
}
...
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
this.backHandler.remove()
}
handleBackPress = () => {
console.log("NativeModules", NativeModules); // this is always {}
console.log("SettingsPageModule", SettingsPageModule); // this is null only when the
// rendered button is pressed
SettingsPageModule.exitSettingsPage();
}
...
render() {
return (
...
<Button transparent onPress={ this.handleBackPress }>
<Icon name='arrow-back' />
</Button>
...
)
}
}
When the device back button is pressed, SettingsPageModule
gets the value {"exitSettingsPage": [Function fn], "getConstants": [Function anonymous]}
, but when the rendered button is pressed, it gets null
, which makes my app crash. This is really strange that the same object, used in the same function has different values for different calls.
Does anyone know why this is happening? Does the event listener for the BackHandler
call the function differently?