React-Native(二) 統(tǒng)一Navigator 及Fragment 多入口

在原生項目里面加入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注冊組件即可鼻由。
這樣入口組件就不止一個了,個人感覺其實不是很合理,只能說可以解決需求問題蕉世。如果有好的解決方案蔼紧,希望不吝賜教~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市狠轻,隨后出現(xiàn)的幾起案子奸例,更是在濱河造成了極大的恐慌,老刑警劉巖向楼,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件查吊,死亡現(xiàn)場離奇詭異,居然都是意外死亡湖蜕,警方通過查閱死者的電腦和手機逻卖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來昭抒,“玉大人评也,你說我怎么就攤上這事「曷常” “怎么了仇参?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長婆殿。 經(jīng)常有香客問我诈乒,道長,這世上最難降的妖魔是什么婆芦? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任怕磨,我火速辦了婚禮,結(jié)果婚禮上消约,老公的妹妹穿的比我還像新娘肠鲫。我一直安慰自己,他們只是感情好或粮,可當(dāng)我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布导饲。 她就那樣靜靜地躺著,像睡著了一般氯材。 火紅的嫁衣襯著肌膚如雪渣锦。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天氢哮,我揣著相機與錄音袋毙,去河邊找鬼。 笑死冗尤,一個胖子當(dāng)著我的面吹牛听盖,可吹牛的內(nèi)容都是我干的胀溺。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼皆看,長吁一口氣:“原來是場噩夢啊……” “哼仓坞!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起腰吟,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤扯躺,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蝎困,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體录语,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年禾乘,在試婚紗的時候發(fā)現(xiàn)自己被綠了澎埠。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡始藕,死狀恐怖蒲稳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情伍派,我是刑警寧澤江耀,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站诉植,受9級特大地震影響祥国,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜晾腔,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一舌稀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧灼擂,春花似錦壁查、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至峻贮,卻和暖如春席怪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背月洛。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工何恶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留孽锥,地道東北人嚼黔。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓细层,卻偏偏與公主長得像,于是被迫代替她去往敵國和親唬涧。 傳聞我的和親對象是個殘疾皇子疫赎,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容