- 導(dǎo)航器傳遞參數(shù)給路由
- 往導(dǎo)航欄傳遞參數(shù)
- RN與原生模塊通信
導(dǎo)航器傳遞參數(shù)給路由
示例:同導(dǎo)航器內(nèi)的TestScreen1往TestScreen2傳遞了兩個(gè)參數(shù){params1:"1111",params2:"2222"}
APP.js
const taskNavigator = createStackNavigator({
test1:TestScreen1,
test2:TestScreen2
})
TestScreen1.js
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>第一個(gè)界面!</Text>
<Button onPress = { () =>{
this.props.navigation.navigate('test2',{params1:"1111",params2:"2222"})
}}
title = "進(jìn)入第二個(gè)界面"/>
</View>
);
TestScreen2.js
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>第二個(gè)界面!</Text>
<Text>{"params1 = " + this.props.navigation.state.params.params1}</Text>
<Text>{"params2 = " + this.props.navigation.getParam("params2",2)}</Text>
<Text>{"params3 = " + this.props.navigation.getParam("params3",3)}</Text>
</View>
);
}
獲取時(shí)可用兩種方式,
第一種navigation.getParam(paramName,defaultValue)
饥漫,參數(shù)不存在時(shí)答姥,取默認(rèn)值
第二種navigation.state.params. paramName
, 如果未指定參數(shù),它的值是 null抱虐。
往導(dǎo)航欄傳遞參數(shù)
使用this.props.navigation.setParams({paramName1: paramValue1,paramName2: paramValue2,...})
的方式向?qū)Ш綑趥髦?br>
在導(dǎo)航欄中使用navigation.getParam(paramName,defaultValue)
取值
export default class TestScreen1 extends Component {
_paramsValue = 0;
static navigationOptions = ({ navigation }) => {
return {
title: '第一個(gè)界面' + navigation.getParam("param",""),
headerLayoutPreset: "center",
headerTitleStyle: {
fontWeight: 'normal',
fontSize: 16,
flex: 1,
textAlign: 'center'
},
headerStyle: {
backgroundColor: 'white',
elevation: 5,
},
}};
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>第一個(gè)界面!</Text>
{/* <Button onPress = { () =>{
this.props.navigation.navigate('test2',{params1:"1111",params2:"2222"})
}}
title = "進(jìn)入第二個(gè)界面"/> */}
<Button onPress = { () =>{
this.props.navigation.setParams({param: ++this._paramsValue})
}}
title = "+1"/>
</View>
);
}
}
RN與原生模塊通信
一.RN 調(diào)用安卓代碼
經(jīng)常會(huì)用到的場景比如獲取一些安卓本地緩存數(shù)據(jù)等
具體步驟如下:
1.在Android端創(chuàng)建一個(gè)繼承ReactContextBaseJavaModule
的類亩鬼,實(shí)現(xiàn)getName()
方法,用來返回RN尋找到該類的名稱
public class ClientModule extends ReactContextBaseJavaModule {
private ReactContext mReactContext;
public ClientModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
}
@Override
public String getName() {
return "ClientModule";
}
}
2.創(chuàng)建用于RN調(diào)用的方法烘挫,用@ReactMethod
注解修飾
@ReactMethod
public void showToast(String message) {
Toast.makeText(mReactContext,message,Toast.LENGTH_SHORT).show();
}
這里創(chuàng)建了一個(gè)彈出原生Toast的方法诀艰。
3.創(chuàng)建一個(gè)實(shí)現(xiàn)ReactPackage
接口的類,用來管理原生模塊的Model饮六,將繼承了ReactContextBaseJavaModule
的Model添加進(jìn)去
public class ClientPackage implements ReactPackage {
@Nonnull
@Override
public List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ClientModule(reactContext));
return modules;
}
@Nonnull
@Override
public List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
4.將創(chuàng)建好的ClientPackage
添加到包管理列表中
public class MainApplication extends Application implements ReactApplication {
public static Context mContext;
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNGestureHandlerPackage(),
new ClientPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
mContext = getApplicationContext();
}
}
5.在RN中調(diào)用
導(dǎo)入組件
import {NativeModules} from 'react-native';
const clientModule = NativeModules.ClientModule;
在需要彈出的地方調(diào)用
<Button onPress = { () =>{
clientModule.showToast('這是一個(gè)原生Toast')
}}
title = "彈出原生Toast"/>
二. Promise 機(jī)制與安卓原生代碼通信
Promise 機(jī)制需要在原生代碼中創(chuàng)建一個(gè)橋接方法其垄,當(dāng)方法的最后一個(gè)參數(shù)書一個(gè)Promise
對象時(shí),該方法會(huì)返回給js一個(gè)與之對應(yīng)的Promise
對象
原生代碼,在ClientModule
中新增一個(gè)橋接方法
@ReactMethod
public void rnCallNativePromise(String message, Promise promise){
Toast.makeText(mReactContext,message,Toast.LENGTH_SHORT).show();
//得到組件名稱
String componentName = getCurrentActivity().getComponentName().toString();
promise.resolve(componentName);
}
在js中調(diào)用
<Button onPress = { () => {
clientModule.rnCallNativePromise('promise 彈出原生Toast')
.then((msg) => {
Alert.alert('promise 收到消息', msg)
}).catch((error) => {
console.log(error)
}
)}
}
title = "promise 彈出原生Toast"/>
</View>
三.使用callback回調(diào)方式與安卓原生代碼通信
原生代碼,在ClientModule
中新增一個(gè)橋接方法卤橄,傳入一個(gè)成功和失敗的Callback
回調(diào)
@ReactMethod
public void rnCallNativeCallback(Callback success, Callback error) {
try {
success.invoke(100, 200);
} catch (Exception e) {
error.invoke(e.getMessage());
}
}
在js端調(diào)用
<Button
onPress={() => {
clientModule.rnCallNativeCallback((x, y) => {
Alert.alert('callback 收到消息', x + ',' + y)
}, (error) => {
console.log(error)
})
}
}
title="rn CallBack" />
四.使用RCTDeviceEventEmitter
與原生通信
RCTDeviceEventEmitter
類似一個(gè)EventBus
消息傳遞機(jī)制绿满,有發(fā)送方和接收方,與EventBus
類似窟扑,在接收方需要注冊監(jiān)聽喇颁,并在生命周期結(jié)束后取消監(jiān)聽
1.通過ReactApplicationContext
的getJSModule
方法獲取到RCTDeviceEventEmitter
, 調(diào)用emit(eventName, paramss)
方法發(fā)送一個(gè)消息事件
因并不是原生代碼所有的地方都有reactContext
,所有建立一個(gè)工具類嚎货,在rn的model被加載后給工具類的靜態(tài)變量reactContext
賦值
ClientModule:
public ClientModule(@Nonnull ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
ToReactNativtUtil.reactContext = reactContext;
}
ToReactNativtUtil:
public class ToReactNativtUtil {
public static ReactApplicationContext reactContext;
public static void sendEvent(String eventName, @Nullable WritableMap paramss) {
if(reactContext == null)return;
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, paramss);
}
}
需要發(fā)送消息的地方
這里是直接在MainActivity
啟動(dòng)后延時(shí)2s給RN發(fā)送一個(gè)登陸成功的事件橘霎,并傳遞一個(gè)userName參數(shù)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UiInstance.getInstance().postRunnableDelayedToHandler(new Runnable() {
@Override
public void run() {
//給RN發(fā)送一個(gè)loginSucc的事件
WritableMap writableMap= Arguments.createMap();
writableMap.putString("userName","wenny");
ToReactNativtUtil.sendEvent("loginSucc",writableMap);
}
},2000);
}
2.在RN中通過DeviceEventEmitter
來監(jiān)聽事件
import { DeviceEventEmitter } from 'react-native';
componentDidMount() {
DeviceEventEmitter.addListener('loginSucc', (writableMap) => {
Alert.alert('接收到 loginSucc userName :', writableMap.userName)
});
}
componentWillUnmount() {
//移除監(jiān)聽
this.subscription.remove();
}
五.利用getLaunchOptions
方法向js傳遞一個(gè)Bundle
類型的數(shù)據(jù)
這種傳遞方式適用場景有:A
(原生Activity)進(jìn)入B
(ReactActivity)時(shí)需要將A中的某些參數(shù)傳遞給B
的js組件中。
原生端發(fā)送:
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
@Nullable
@Override
protected Bundle getLaunchOptions() {
Bundle bundle = new Bundle();
bundle.putString("newsItemId","123");
bundle.putString("newsItemName","新聞標(biāo)題1");
return bundle;
}
};
}
在js端的入口組件中獲取厂抖,并通過導(dǎo)航器傳參給路由
App.js
class App extends Component {
appContainer
constructor(props) {
super(props);
var newsItemId = this.props.newsItemId;
var newsItemName = this.props.newsItemName;
let stack = createStackNavigator({
test1: TestScreen1,
test2: TestScreen2
}, {
initialRouteParams: {
newsItemId: newsItemId,
newsItemName: newsItemName
},
})
this.appContainer = createAppContainer(stack)
}
render() {
return <this.appContainer />;
}
}
AppRegistry.registerComponent("VideoProject", () => App);
TestScreen1.js
<Text >{navigation.getParam("newsItemId","-") +' ' + navigation.getParam("newsItemName","-")}</Text>