简体   繁体   中英

Adding items to Android React Native Developer menu

In React Native when making development builds you can shake the device or use the menu button to bring up a developer menu. How do you add an additional custom item to this menu? I haven't been able to find any documentation on adding another item but I think it would be very handy to say toggle between server environments (dev, prod, etc.) from the dev menu rather than making separate builds to test against each environment.

The DevSupportManager class can do this for you. You can get it from your ReactNativeHost instance via its ReactInstanceManager :

ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
DevSupportManager devSupportManager = reactInstanceManager.getDevSupportManager();

With that in hand, add a custom dev option as follows:

devSupportManager.addCustomDevOption("Custom dev option", new DevOptionHandler() {
    @Override
    public void onOptionSelected() {
        Toast.makeText(MainActivity.this, "Hello from custom dev option", Toast.LENGTH_SHORT).show();
    }
});

Where you get hold of your ReactNativeHost instance in the first place depends on how you've structured your app. If you created the app using react-native init , your main application class will include this:

@Override
public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
}

...which you could call.

I have a complete sample here ; look at MainActivity .OnCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MainApplication application = (MainApplication) getApplication();
    ReactNativeHost reactNativeHost = application.getReactNativeHost();
    ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
    DevSupportManager devSupportManager = reactInstanceManager.getDevSupportManager();
    devSupportManager.addCustomDevOption("Custom dev option", new DevOptionHandler() {
        @Override
        public void onOptionSelected() {
            Toast.makeText(MainActivity.this, "Hello from custom dev option", Toast.LENGTH_SHORT).show();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM