在原生項目里面加入React-Native之后撩扒,我進行了React-web的融合磨确、多Fragment嵌入的實踐拆魏,以及統(tǒng)一Navigator和平行Router的嘗試。PS:占位補圖 绰寞。項目地址
需求
首先需要說明一下需求:
(一) Navigator
- React-Native在原生項目中需要考慮多頁面跳轉(zhuǎn)的問題豪墅,導(dǎo)航棧的管理很重要泉手。
- 頁面之間的數(shù)據(jù)傳遞。
- 完成了導(dǎo)航棧偶器,怎么能不實現(xiàn)titlebar呢...
(二)多入口
- 項目中仍然是原生大于React螃诅,如何處理零碎化的RN界面啡氢。
- 部分Fragment中需要引入RN。
Navigator
官方文檔中提到的導(dǎo)航器navigator使用純JavaScript實現(xiàn)了一個導(dǎo)航棧术裸,根據(jù)給出的demo我們可以很容易實現(xiàn)頁面跳轉(zhuǎn)功能倘是。
但是這還不夠,在原生項目中袭艺,我需要統(tǒng)一導(dǎo)航棧搀崭,方便數(shù)據(jù)傳遞和頁面切換。
return (
<Navigator
initialRoute={{ title: 'My Initial Scene', index: 0 }}
renderScene={(route, navigator) => {
return <MyScene title={route.title} />
}}
/>
);
initialRoute
初始屬性猾编,renderScene
定義路由入口(路由概念)瘤睹。
將Navigator提升到自定義的component中:
export default class AppNavigator extends Component {
constructor(props) {
super(props);
}
render() {
return ( < Navigator initialRoute = {
{
//配置路由
id: this.props.id,
data: this.props.data,
name: this.props.name,
component: this.props.component
}
}
renderScene = {
(route, navigator) => {
let Scene = route.component;
return <Scene
id={route.id}
data={route.data}
name={route.name}
component={route.component}
navigator={navigator}
/>
}
}
style = {
styles.navigatorstyle
}
configureScene = {
(route) => {
//配置路由跳轉(zhuǎn)效果
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.PushFromRight;
}
}
/>
);
}
}
const styles = StyleSheet.create({
navigatorstyle: {
flex: 1
}
});
在initialRoute
中,我們配置路由傳遞的信息:
id: this.props.id,//ID答倡,唯一標(biāo)識
data: this.props.data,//傳遞的數(shù)據(jù)
name: this.props.name,//字符資源
component: this.props.component//當(dāng)前組件
renderScene中我們將配置的這些參數(shù)當(dāng)做一個View組件傳遞回去轰传,這些參數(shù)成為下一個組件的屬性:this.props
,這樣我們就可以獲取到navigator對象,并進行push,pop操作瘪撇。
在入口文件index.android.js
中:
return (
//統(tǒng)一的入口
<AppNavigator id='Settings' data='' name='' component={Settings} />
);
指定setting組件為導(dǎo)航棧棧底組件获茬,因為是入口所以沒有data參數(shù)可以傳遞。在setting中實現(xiàn)業(yè)務(wù)需求:
'use strict';
import React, {
Component
} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
BackAndroid,
ToastAndroid,
Platform
} from 'react-native';
import {
Button,
List
} from 'antd-mobile';
import Third from './Third';
const Item = List.Item;
const Brief = Item.Brief;
export default class Settings extends Component {
constructor(props) {
super(props);
}
_onClick() {
const navigator = this.props.navigator;
if (navigator) {
navigator.push({
id: 'thirdpage',
data: '',
name: 'third',
component: Third
});
}
}
render() {
return (
<View style = {styles.container}>
<List renderHeader={()=> '個人設(shè)置1'}>
<Item arrow="horizontal" navigator={this.props.navigator} onClick={this._onClick.bind(this)} >
第一個標(biāo)題
</Item>
<Item arrow="horizontal" onClick={()=>{}}>
第二個標(biāo)題
</Item>
<Item arrow="horizontal" onClick={()=>{}}>
第三個標(biāo)題
</Item>
<Item arrow="horizontal" onClick={()=>{}}>
第四個標(biāo)題
</Item>
<Item arrow="horizontal" onClick={()=>{}}>
第五個標(biāo)題
</Item>
</List>
</View>
)
};
/*
* 生命周期
*/
componentDidMount() {
this._addBackAndroidListener(this.props.navigator);
}
componentWillUnmount() {
this._removeBackAndroidListener();
}
//監(jiān)聽Android返回鍵
_addBackAndroidListener(navigator) {
if (Platform.OS === 'android') {
var currTime = 0;
BackAndroid.addEventListener('hardwareBackPress', () => {
if (!navigator) {
return false;
}
const routers = navigator.getCurrentRoutes();
if (routers.length == 1) { //在主界面
var nowTime = (new Date()).valueOf();
if (nowTime - currTime > 2000) {
currTime = nowTime;
ToastAndroid.show("再按一次退出RN", ToastAndroid.SHORT);
return true;
}
return false;
} else { //在其他子頁面
navigator.pop();
return true;
}
});
}
}
//移除監(jiān)聽
_removeBackAndroidListener() {
if (Platform.OS === 'android') {
BackAndroid.removeEventListener('hardwareBackPress');
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
}
});
其中我們在行組件Item
中定義了點擊跳轉(zhuǎn)動作倔既,在onclick函數(shù)中將下一個組件信息push入棧恕曲,基本的入棧過程就完成了。
- 注意渤涌,
Item
中并沒有navigator對象佩谣,而是this.props
傳遞給它的。 - 在代碼中我同時添加了Android物理按鍵的監(jiān)聽实蓬,如果監(jiān)聽到物理回退鍵茸俭,那么就執(zhí)行退棧的操作。
到這里navigator差不多就構(gòu)建完成了安皱。
多入口
- fragment中使用RN,區(qū)別與activity中的使用是因為调鬓,在activity中ReactRootView替換了原生
creatView
中返回的view。
同樣的我們實現(xiàn)一個父層Fragment练俐,替換掉onCreatView
中返回的View袖迎,就可以渲染js了:
public abstract class ReactFragment extends Fragment {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
/**
* 返回appregistry注冊的名字.
* @return
*/
public abstract String getMainComponentName();
@Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
mReactInstanceManager =
((ReactApplication) getActivity().getApplication())
.getReactNativeHost()
.getReactInstanceManager();
}
/**
* 這里改寫根View為ReactRootView,因此繼承此類的fragment實現(xiàn)`getMainComponentName`即可.
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Nullable
@Override
public ReactRootView onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return mReactRootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(
mReactInstanceManager,
getMainComponentName(),
null
);
}
}
同時冕臭,我們需要自定義的Application實現(xiàn)ReactApplication:
public class ReactApplication extends Application implements com.facebook.react.ReactApplication{
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return true;
}
@Override
public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
實現(xiàn)了根Fragment后腺晾,子類繼承并返回注冊的組件名即可:
public class TestFragment extends ReactFragment {
@Override
public String getMainComponentName() {
return "thirdfragment";
}
}
但,還有一點事情沒有做辜贵,掛載的Activity還需要實現(xiàn)DefaultHardwareBackBtnHandler
接口悯蝉,以保證RN的生命周期。
參考
public class FragmentActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
/**
* Get the reference to the ReactInstanceManager
*/
mReactInstanceManager =
((MyApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
/*
* We can instantiate a fragment to show for Activity programmatically,
* or using the layout XML files.
* This doesn't necessarily have to be a ReactFragment, any Fragment type will do.
*/
Fragment viewFragment = new HelloFragment();
getFragmentManager().beginTransaction().add(R.id.container, viewFragment).commit();
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
/*
* Any activity that uses the ReactFragment or ReactActivty
* Needs to call onHostPause() on the ReactInstanceManager
*/
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
/*
* Same as onPause - need to call onHostResume
* on our ReactInstanceManager
*/
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
}
剩下的工作則是完成RN組件的編寫托慨,并AppRegistry
注冊組件即可鼻由。
這樣入口組件就不止一個了,個人感覺其實不是很合理,只能說可以解決需求問題蕉世。如果有好的解決方案蔼紧,希望不吝賜教~