android - react native Android : Creating a simple module

标签 android reactjs react-native

我正在尝试运行最基本的 React Native 示例,其中我试图更改传递给自定义 java 模块的文本:

我的index.android.js 文件:

var React = require('react-native');
var Image = React.Image;
var Button= require('react-native-button');
var NativeModules = React.NativeModules;
var TouchableNativeFeedback = React.TouchableNativeFeedback;

var Directory2 = React.createClass({
render: function() {
  var layout =
      <React.View style = { styles.parent } >
          <React.Text>
              Enter Host :
          </React.Text>

          <React.TextInput
              onChangeText={(e) => this.setState({input: e})}
              text = { this.state.input }
              onSubmitEditing = { this.showMeaning }
          />

          <Image source={ this.state.setImg } style={styles.img} />

          <Button
            style={styles.button}
            onPress={this._handlePress}>
            Test
          </Button>
      </React.View>
  ;
  return layout;
},
getInitialState: function() {
return {
    input : '',
    setImg : require('image!red'),
    text: 'Goodbye World.'
};
},
showMeaning: function() {
  // Use the ternary operator to check if the word 
  // exists in the dictionary.
  var meaning = "you entered some text";

  // Update the state
  this.setState({
       output: meaning 
  });
},
_handlePress: function() {
  this.setState({
      setImg : require('image!green')
 });

  require('NativeModules').PingModule.processString( this.state.text, (text) => { alert(text); });
 },
 });

var styles = React.StyleSheet.create({

// For the container View
parent: {
    padding: 16
},

img : {
  alignSelf : 'flex-start'
},

button: {
  textAlign : 'center',
  backgroundColor : '#FF0000',
  width : 100,
  alignSelf : 'flex-end'
},

buttonText: {
  fontWeight: 'bold'
},
});

React.AppRegistry.registerComponent('Directory2', function() {
   return Directory2;
});

我的 MainActivity.java 文件:

package com.directory2;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

// Add extra packages here
import com.directory2.CustomPackages;

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()) // Add packages here!
            .addPackage(new CustomPackages()) // <-- and here
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "Directory2", 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, this);
    }
}
}

我的 React 包文件:

package com.directory2;


import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import java.util.Arrays;
import java.util.List;

public class CustomPackages implements ReactPackage {

@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  List<NativeModule> modules = new ArrayList<>();
  modules.add(new PingModule(reactContext));
  return modules;
}

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

public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
  return Collections.emptyList();
}

}

还有我的模块文件:

package com.directory2;

import com.facebook.react.bridge.ReactContextBaseJavaModule;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.NativeModule;

public class PingModule extends ReactContextBaseJavaModule {

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

// Available as NativeModules.MyCustomModule.processString
@ReactMethod
public void processString(String input, Callback callback) {
    callback.invoke(input.replace("Goodbye", "Hello"));
}

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

项目构建,但是当我单击“测试”按钮时

require('NativeModules').PingModule.processString( this.state.text, (text) => { alert(text); });

上面的行抛出错误

undefined is not an object (evaluating 'require('NativeMobules').PingModule.processString')

最佳答案

将此代码添加到 PingModule 的末尾 -

export default PingModule;

您必须导出模块才能使其可用。

关于android - react native Android : Creating a simple module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34939861/

相关文章:

android - 如何在Android分页库中为列表、过滤器和搜索维护相同的数据源

java - 单击按钮时将 fragment 添加到寻呼机适配器

javascript - 对 react-data-grid 有效的 onBlur

html - 当我们向文本添加上边距时,它会向 div 而不是文本添加边距

javascript - 用于处理 Ajax 数据的设计模式。正确的方法是什么?

javascript - React-native formik 表单引用始终为空

android加速度计来测量速度

android - 在 Android 中支持针对相应 API 级别的相同 View 的不同外观

swift - 在 OSX 或 Windows (VM)、React Native 还是 Swift 上进行 iOS 开发?

react-native - 使用 Facebook 登录时不会触发 onLoginFinished 回调