Load the React Native page

React Native maintains a routing table similar to React, and then loads an index.android.bundle from RN and passes in a property named routerName as the convention. Then, the routing table matches the routerName and loads the corresponding page

React Native notification events to React Native

Similar to publish and subscribe model

The native side emits a global notification event, the RN side listens for this event, executes its own logic, and removes the event after the page is destroyed. The implementation code looks like this

import { Platform, DeviceEventEmitter, NativeEventEmitter } from 'react-native';
const PLAN_EVENT_MAP = {
  // Modify plan success event
  PlanChangeSuccess: 'PlanChangeSuccess'};const FOO = (props) = > {
  // Refresh the event Manager ref on the details page after the modification is successful
  const eventReloadRef = useRef();
  // Initialize the fetch data
  const getInitialDetail = () = > {};
  useEffect(() = > {
    getInitialDetail();
    () = > {
      // Remove listening on native eventseventReloadRef.current && eventReloadRef.current.remove(); }; } []);/** * listen for natively sent events (global) */
  useEffect(() = > {
    / / the Android side
    if (Platform.OS === 'android') {
      eventReloadRef.current = DeviceEventEmitter.addListener(
        PLAN_EVENT_MAP.PlanChangeSuccess,
        (success) = > {
          console.log('android PlanChangeSuccess', success);
          // Reload data after updatingsuccess && getInitialDetail(); }); }/ / the iOS side
    if (Platform.OS === 'ios') {
      const EventEmitterManager = NativeModules.VKReactEventEmitter;
      if (EventEmitterManager) {
        const navigationEmitter = new NativeEventEmitter(EventEmitterManager);
        eventReloadRef.current = navigationEmitter.addListener(
          PLAN_EVENT_MAP.PlanChangeSuccess,
          (success) = > {
            console.log('ios PlanChangeSuccess', success);
            // Reload data after updatingsuccess && getInitialDetail(planId); }); }}// eslint-disable-next-line react-hooks/exhaustive-deps} []); };Copy the code

Usage scenarios

For example, in a detail page provided by RN, there is a modification function that jumps to the original modification content page. When the content is modified and returned to the details page, RN needs to be notified to update the detail page.

React Native calls Native methods

Initializers get and assign parameters passed in natively

First, as we mentioned earlier, React Native initializes a Routing table similar to React when the app is started. It then loads a bundle packed by RN and passes in a property named routerName with the agreed routerName. The RN will receive the routerName props as an initialRouteName to load the page.

Let’s just look at the code

import React from 'react';
import { createAppContainer, createStackNavigator } from 'react-navigation';
import HomePage from '.. /pages/home';
const routes = {
  HomePage: {
    screen: HomePage, //Tab as a Stack route}};class Routers extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    // This is an RN Bundle loaded natively
    if (this.props.routerName) {
      // Initialize the routing page based on the routerName passed in native
      options.initialRouteName = this.props.routerName;
      const keys = Object.keys(routes);
      keys.forEach((key) = > {
        routes[key].params = {};
      });
      routes[this.props.routerName].params = {
        // Any RN Bundle loaded natively is currently a native environment
        isNative: true.// Other attributes that are passed in natively are assigned to the params attribute of the current route. this.props, }; }const StackNavigator = createAppContainer(
      createStackNavigator(routes, options)
    );
    return <StackNavigator />; }}Copy the code

Then, in the loaded page, you can download frompropsObject to get properties and methods passed in natively

Here’s what the code looks like

  • frompropsGets the parameters passed in natively
import { NativeModules } from 'react-native';
function getNativeModuleParams(props) {
  const { state = {} } = props.navigation || {};
  const { params = {} } = state;
  // Select_Content is a select_content parameter with native conventions, and the value is a JSON string, because sending json objects natively has problems
  const { nativeParams = '{}'. rnParams } = params;const nativeModuleParams = JSON.parse(nativeParams);
  return {
    rnParams,
    nativeModuleParams,
  };
}

const Page = (props) = > {
  // Get the data passed in native is a serialized object, which has been deserialized
  const { nativeModuleParams = {}, rnParams = {} } =
    getNativeModuleParams(props) || {};
  const { isNative } = rnParams || {};
  // The parameter name conforms to the native convention
  let {
    nativeParams, // The argument passed in native
    nativeMethod, // The native incoming method
    moduleName,
  } = isNative ? nativeModuleParams : rnParams; // isNative ? Parameters passed by native jumps: Parameters passed by RN jumps
};
Copy the code
  • Call the method passed in natively
const handleMethod = useCallback(() = > {
  // Call the method passed in natively
  // This nativeMethod is a key of the nativeMethod method name
  if (NativeModules[moduleName] && NativeModules[moduleName][nativeMethod]) {
    NativeModules[moduleName][nativeMethod]({
      nativeParams,
    });
  }
}, [nativeMethod, moduleName, nativeParams]);
Copy the code

Usage scenarios

For example, the native side uses a modal box of RN. When RN turns off the modal box, it can be seen that it has disappeared, but the container containing the modal box has not been destroyed. It is created natively and cannot be operated by RN. On iOS, it is a ViewController, and on Android, it is an Activity. There can only be one on the same page. Therefore, RN needs to notify the native to destroy the container, which can be destroyed by calling the method provided by the native.

conclusion

This paper mainly introduces the communication process between React Native APP and React Native APP in the development process. At present, it is based on the logic of their own business scenarios, readers can be customized according to their own business needs, welcome to communicate, interested can pay attention to my Github[github.com/], exchange and study together 😊