React Native Android:创建一个简单的模块

时间:2016-01-22 05:49:51

标签: 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";
}
}

项目建立但是当我点击&#34;测试&#34;按钮

  

require(&#39; NativeModules&#39;)。PingModule.processString(this.state.text,(text)=&gt; {alert(text);});

以上行抛出错误

  

undefined不是一个对象(评估&#39; require(&#39; NativeMobules&#39;)。PingModule.processString&#39;)

1 个答案:

答案 0 :(得分:3)

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

export default PingModule;

你必须导出模块才能使它们可用。