1, we already said that. In the RN hybrid development, native how to call JS's each page JS how to invoke the native activity, and how to call the native method in JS.
2 of these have been relatively simple, this section mainly says, if we are in native Java code, some time very want to respond to JS a method to do.
At present, I have not learned how to directly call JS a method, my approach is to use the event response, and the original Android button to bind an event, if you receive this message, JS end to perform this operation. Here is a specific word. 1 Java Side registration Events
How to register the time?
public static void Sendevent (Reactcontext reactcontext, String eventName, @Nullable writablemap Paramss)
{
if ( Reactcontext!=null) {
reactcontext.getjsmodule (DeviceEventManagerModule.RCTDeviceEventEmitter.class). Emit ( EventName, PARAMSS);
}
In this code, is a way to send to the JS-side event, which reactcontext this context, is in the reactmodule of this class. It inherits Reactcontextbasejavamodule this class. It should be clear to understand,
We can set the static variable in the desired class, and then pass the object in the constructor of the Reactmodule class.
public static Reactcontext Mreactcontext;
EventName This parameter, is the name of the event.
Paramss This parameter is an argument to the event.
2 Java-side Send message
We want to invoke the Java side of the JS method, that is, through the message to determine which method to call, with the previous section, called JS activity, JS only an activity, but it has a lot of pages, specifically show which page, can pass through our parameters to distinguish.
Writablemap event = Arguments.createmap ();
Event.putstring ("type", "abc");
Sendevent (Mreactcontext, "ABC", event);
The first two lines of code are set parameters, and the last method is to send data.
Below we look at how the JS end is received and processed. 3 JS terminal receiving and processing
Deviceeventemitter This is the JS-side Setup Registration event that requires the component to be used.
Import {
appregistry,
deviceeventemitter,
} from ' react-native ';
See this code, it should be easier to understand. We register the received events at the beginning of the JS component lifecycle.
This. ABC = deviceeventemitter.addlistener (' abc ', function (e:event) {
if (' abc ' = = E.type) {
that.setstate ({Abc:tru e});
This code can be written in the life cycle of Componentdidmount, AddListener (' abc ', the place of ABC and sendevent (Mreactcontext, "ABC", event); The ABC in this is corresponding.
if (' abc ' = = E.type) {The type of this place and ABC and event.putstring ("type", "abc"); This is the corresponding, it is more clear than this.
In this case, when the Java end of the message, I received in the JS end, received after, want to implement what method is my business, this demand can be satisfied.