React Native:Android Native传递参数到React Native中
1、通过重写 ReactActivityDelegate 方法传入参数,Activity代码如下:
import android.app.Activity;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.bridge.ReactContext;
public class RnTestActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
private ReactContext mainreactContext;
private boolean ad = true;
@Override
protected String getMainComponentName() {
return "TestProject";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new MyReactDelegate(this,getMainComponentName());
}
//自定义MyReactDelegate
class MyReactDelegate extends ReactActivityDelegate {
public MyReactDelegate(Activity activity
, @javax.annotation.Nullable String mainComponentName) {
super(activity, mainComponentName);
}
@javax.annotation.Nullable
@Override
protected Bundle getLaunchOptions() {
Bundle bundle = new Bundle();
bundle.putString("params","activity传递的参数");
return bundle;
}
}
}
2、在index.android.js中获取参数,js代码如下:
import React,{Component} from 'react';
import {AppRegistry,StyleSheet,Text,View,AppState,TouchableOpacity,Image,Button} from 'react-native';
import app3 from './myapp';
import ChatScreenA from './projectlist'; //从另外一个js文件中获取名为ChatScreenA的Component
import codePush from 'react-native-code-push'; //用于热更新,此案例中可以不用管。
import { StackNavigator } from 'react-navigation'; //js界面间的导航,此案例中可以不用管。
let codePushOptions = { checkFrequency: codePush.CheckFrequency.ON_APP_RESUME };
export default class myapp extends Component{
constructor(props){
super(props);
this.state ={
message:props.params //这里通过props接收参数,params为获取参数的key值
}
}
componentDidMount(){
codePush.sync({
updateDialog: true,
installMode: codePush.InstallMode.IMMEDIATE
});
}
render(){
var initProps = this.props.params;
return(
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started
</Text>
<Text style={styles.instructions}>
{this.state.message} //传入的参数在这里展示,展示结果应该是:activity传递的参数
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF'
},
welcome:{
fontSize:20,
margin:10,
textAlign:'center'
},
instructions:{
textAlign:'center',
color:'#333333',
marginBottom:5
}
});
AppRegistry.registerComponent('TestProject',()=>codePush(codePushOptions)(myapp));
本文参考以下资料:http://blog.csdn.net/zach_zhou/article/details/71305139