反应所需的原生未知模块定制机组件 [英] React native Required Unknown Module for custom native component

查看:284
本文介绍了反应所需的原生未知模块定制机组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现自定义本地组件的ReactNative。按文件我创造了我所有的组件,如以下。不过还是我得到的错误要求未知模块MyCustomToast。请帮我解决这个问题。

SampleToast.java: -

 公共类SampleToast扩展ReactContextBaseJavaModule {
公共SampleToast(ReactApplicationContext reactContext){
    超(reactContext);
}@覆盖
公共字符串的getName(){
    返回MyCustomToast
}@ReactMethod
公共无效showToast(字符串消息){
    Toast.makeText(getReactApplicationContext(),消息,Toast.LENGTH_LONG).show();
}

}

MakeReactPackage.java: -

 公共类MakeReactPackage实现ReactPackage {
@覆盖
公开名单< NativeModule> createNativeModules(ReactApplicationContext reactContext){    清单< NativeModule>模块=新的ArrayList<>();
    modules.add(新SampleToast(reactContext));
    返回模块;}@覆盖
公开名单<&级LT ;?扩展JavaScriptModule>> createJSModules(){
    返回Collections.emptyList();
}@覆盖
公开名单< ViewManager> createViewManagers(ReactApplicationContext reactContext){
    返回Arrays.asList();
}

}

MainActivity.java: -

 公共类MainActivity扩展活动实现DefaultHardwareBackBtnHandler {私人ReactInstanceManager mReactInstanceManager;
私人ReactRootView mReactRootView;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    mReactRootView =新ReactRootView(本);    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName(index.android.bundle)
            .setJSMainModuleName(index.android)
            .addPackage(新MainReactPackage())
            .addPackage(新MakeReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            。建立();    mReactRootView.startReactApplication(mReactInstanceManager,HelloWorldBha,NULL);    的setContentView(mReactRootView);
}@覆盖
公共布尔的onkeyup(INT键code,KeyEvent的事件){
    如果(键code == KeyEvent.KEY code_MENU&放大器;&安培;!mReactInstanceManager = NULL){
        mReactInstanceManager.showDevOptionsDialog();
        返回true;
    }
    返回super.onKeyUp(键code,事件);
}@覆盖
公共无效onBack pressed(){
    如果(mReactInstanceManager!= NULL){
        mReactInstanceManager.onBack pressed();
    }其他{
        super.onBack pressed();
    }
}@覆盖
公共无效invokeDefaultOnBack pressed(){
    super.onBack pressed();
}@覆盖
保护无效的onPause(){
    super.onPause();    如果(mReactInstanceManager!= NULL){
        mReactInstanceManager.onPause();
    }
}@覆盖
保护无效onResume(){
    super.onResume();    如果(mReactInstanceManager!= NULL){
        mReactInstanceManager.onResume(本);
    }
}}

和在JS

反应-native.js: -

  MyCustomToast:需要('MyCustomToast'),

SampleToast.js: -

 使用严格的;/ **
 *这暴露了本土ToastAndroid模块作为JS模块。这有一个功能秀
 *这需要以下参数:
 *
 * 1.字符串消息:用文字来敬酒的字符串
 * 2 INT时间:敬酒的持续时间。可能是ToastAndroid.SHORT或ToastAndroid.LONG
 * /
VAR {} NativeModules需要=('反应母语');
module.exports = NativeModules.MyCustomToast;

Index.android.js: -

  / **
 *样本反应本机应用程序
 * https://github.com/facebook/react-native
 * /
使用严格的;VAR阵营=要求('反应母语');
VAR toastMessage =要求('SampleToast')
{VAR
    鸭pregistry,
    样式表
    文本,
    视图,
    NativeModules
    } =动作;
VAR HelloWorldBha = React.createClass({
    渲染:功能(){
        返回(
            <景观风格= {} styles.container GT&;
                <文本样式= {styles.welcome}>
                    欢迎反应原住民!
                < /文本>
                <文本样式= {styles.instructions}>
                    要开始,编辑index.android.js
                < /文本>
                <文本样式= {styles.instructions}>
                    摇动或preSS用于开发菜单菜单按钮
                < /文本>
                toastMessage.show('Bharath库马尔');            < /视图>
        );
    }
});VAR风格= StyleSheet.create({
    容器:{
        软硬度:1,
        justifyContent:中心,
        alignItems:中心,
        的backgroundColor:'#F5FCFF',
    },
    欢迎:{
        字体:20,
        设置textAlign:中心,
        保证金:10,
    },
    说明:{
        设置textAlign:中心,
        颜色:#333333,
        marginBottom:5,
    },
});鸭pregistry.registerComponent('HelloWorldBha',()=> HelloWorldBha);


解决方案

在SampleToast.js使用providesModule注释。所以SampleToast.js变为:

  / **
 * @providesModule SampleToast
 * / 使用严格的; / **
  *这暴露了本土ToastAndroid模块作为JS模块。这有一个功能秀
  *这需要以下参数:
  *
  * 1.字符串消息:用文字来敬酒的字符串
  * 2 INT时间:敬酒的持续时间。可能是ToastAndroid.SHORT或ToastAndroid.LONG
  * /
 VAR {} NativeModules需要=('反应母语');
 module.exports = NativeModules.MyCustomToast;

另外,当您使用需要Index.android.js('SampleToast'),那么你就需要给的相对路径。所以,如果SampleToast.js和Index.android.js住在同一个目录下,你需要

  VAR toastMessage =要求('./ SampleToast');

我个人preFER第一个选项。

I am trying to implement custom native component for ReactNative. As per documentation i created all my components like below. But still i am getting error Required Unknown Module "MyCustomToast". Please help me to resolve this.

SampleToast.java:-

public class SampleToast extends ReactContextBaseJavaModule {


public SampleToast(ReactApplicationContext reactContext) {
    super(reactContext);
}

@Override
public String getName() {
    return "MyCustomToast";
}

@ReactMethod
public void showToast(String message) {
    Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_LONG).show();
}

}

MakeReactPackage.java:-

public class MakeReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {

    List<NativeModule> modules = new ArrayList<>();
    modules.add(new SampleToast(reactContext));
    return modules;

}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Arrays.asList();
}

}

MainActivity.java:-

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("index.android.bundle")
            .setJSMainModuleName("index.android")
            .addPackage(new MainReactPackage())
            .addPackage(new MakeReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorldBha", null);

    setContentView(mReactRootView);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
        mReactInstanceManager.showDevOptionsDialog();
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

@Override
public void onBackPressed() {
    if (mReactInstanceManager != null) {
        mReactInstanceManager.onBackPressed();
    } else {
        super.onBackPressed();
    }
}

@Override
public void invokeDefaultOnBackPressed() {
    super.onBackPressed();
}

@Override
protected void onPause() {
    super.onPause();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onPause();
    }
}

@Override
protected void onResume() {
    super.onResume();

    if (mReactInstanceManager != null) {
        mReactInstanceManager.onResume(this);
    }
}}

And in JS

react-native.js:-

MyCustomToast:require('MyCustomToast'),

SampleToast.js:-

 'use strict';

/**
 * This exposes the native ToastAndroid module as a JS module. This has a function 'show'
 * which takes the following parameters:
 *
 * 1. String message: A string with the text to toast
 * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG
 */
var { NativeModules } = require('react-native');
module.exports = NativeModules.MyCustomToast;

Index.android.js:-

    /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var toastMessage = require('SampleToast')
var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    NativeModules
    } = React;




var HelloWorldBha = React.createClass({
    render: function () {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={styles.instructions}>
                    To get started, edit index.android.js
                </Text>
                <Text style={styles.instructions}>
                    Shake or press menu button for dev menu
                </Text>


                toastMessage.show('Bharath Kumar');

            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

AppRegistry.registerComponent('HelloWorldBha', () => HelloWorldBha);

解决方案

In SampleToast.js use the providesModule annotation. So SampleToast.js becomes:

/**
 * @providesModule SampleToast
 */

 'use strict';

 /**
  * This exposes the native ToastAndroid module as a JS module. This has a function 'show'
  * which takes the following parameters:
  *
  * 1. String message: A string with the text to toast
  * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG
  */
 var { NativeModules } = require('react-native');
 module.exports = NativeModules.MyCustomToast;

Alternatively, when you use require('SampleToast') in Index.android.js then you would need to give the relative path. So if SampleToast.js and Index.android.js live in the same directory you would need

var toastMessage = require('./SampleToast');

Personally, I prefer the first option.

这篇关于反应所需的原生未知模块定制机组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆