搞懂這幾步React Native才算入門

1棺聊、了解目錄結構

2、頁面

2.1組件

2.2布局

2.3樣式

3、頁面跳轉

3.1RN頁面間跳轉

App.js //初始化路由 npm install react-native-deprecated-custom-components安裝Navigator

import React, {Component} from 'react';
import Navigator from 'react-native-deprecated-custom-components';
import A from './src/A'
export default class App extends Component {
    render() {
        let defaultName='A';
        let defaultComponent=A
        return (
            <Navigator.Navigator
                initialRoute={{
                  name:defaultName,
                  component:defaultComponent
                }}
                renderScene={(route,navigator)=>{
                    let Component=route.component;
                    return(<Component {...route.params} navigator={navigator}/>);
                }}

            />
        );
    }
}

A.js

import React,{ Component } from 'react';
import {
    View,ScrollView,Text
} from 'react-native'
import B from './B'
export default class A extends Component{
    //初始化函數(shù)
    constructor(props){//舊版本getInitialState()
        super(props)
        this.state={//定義變量
            id:2,
            user:'Viknando',
            userName:null
        }
    }

    _pressBtn(){
        const{navigator}=this.props;
        const self=this;
        if(navigator){
            navigator.push({//頁面跳轉
                name:'B',
                component:B,
                params:{
                    user:this.state.user,
                    id:this.state.id,
                    //將此方法作為參數(shù)傳到B中調用
                    getUserName:function(userName){
                        self.setState({
                            userName:userName
                        })
                    }
                }
            })
        }
    }

    render(){
        if(this.state.userName){
            return(<View>
                <Text></Text>
                <Text></Text>
                <Text>user:{JSON.stringify(this.state.userName)}</Text>
            </View>)
        }else{
            return(
                <ScrollView>
                    <Text></Text>
                    <Text></Text>
                    <Text onPress={this._pressBtn.bind(this)}>Hello!</Text>
                    <Text onPress={this._pressBtn.bind(this)}>Viknando!</Text>
                </ScrollView>
            )
        }
    }

}

B.js

import React,{ Component } from 'react';
import {
    ScrollView,Text
} from 'react-native'
export default class B extends Component{
    constructor(props){
        super(props)
        this.state={
            id:null
        }
    }

    _pressBtn(){
        const{navigator}=this.props;
        const USER_MODELS={
            1:{name:'Domsting',age:'24'},
            2:{name:'Viknando',age:'20'},

        }
        if(this.props.user){
            let userNameModel=USER_MODELS[this.props.id];
            this.props.getUserName(userNameModel)//B invoked fun of A
        }
        if(navigator){
            navigator.pop();
        }

    }

    render(){
        return(
            <ScrollView>
                <Text></Text>
                <Text></Text>
                <Text>userId:{this.state.id}</Text>
                <Text onPress={this._pressBtn.bind(this)}>author:{this.state.user}</Text>
            </ScrollView>
        )
    }
    componentDidMount(){
        this.setState({
            id:this.props.id,
            user:this.props.user
        })
    }

}

3.2RN與原生頁面間跳轉

原生頁面->RN:
tv_jump_rn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToRN();
            }
        });
public void jumpToRN(){
        Intent intent=new Intent(this,MainActivity.class);//跳轉的怎么是class?
        startActivity(intent);
        this.finish();
    }

Q:跳轉的怎么是class?原來MainActivity繼承了ReactActivity谬运,從而跳轉到了RN頁面。

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "RNjsWithNative";
    }
}

Q:這樣就跳轉了垦藏?我們得知道這幾點:
1梆暖、android工程中MainApplication聲明了ReactApplication,getPackages()返回了new MainReactPackage()掂骏,之后我們添加模塊也要添加Package,我這里添加了new JumpRP()

public class MainApplication extends Application implements ReactApplication {

  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 JumpRP()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

2轰驳、MainActivity中getMainComponentName將我們定義的模塊名:RNjsWithNative返回給了RN,在入口文件我們注冊了RNjsWithNative對應的組件app弟灼,還記得AppRegistry.registerComponent('RNjsWithNative', () => app);么级解?MainActivity與RN對應的app模塊才綁定在了一起

RN頁面->原生

RN頁面的點擊事件代碼是這樣的,startActivityFromJS方法是自定義的?"com.rnjswithnative.BActivity"是包名田绑?

<Text style={styles.welcome}
                      onPress={() => NativeModules.Native_Module.startActivityFromJS("com.rnjswithnative.BActivity", "this msg from RN")}>
                    Jump to NativePage!!!
                </Text>

沒錯勤哗,就是這樣的,在android項目中我們新建了
image.png

我們得知道這幾點:
1掩驱、JumpModule繼承了ReactContextBaseJavaModule芒划,定義了用@ReactMethod修飾的startActivityFromJS方法

@ReactMethod
    public void startActivityFromJS(String name, String params){
        try{
            Activity currentActivity = getCurrentActivity();
            if(null!=currentActivity){
                Class toActivity = Class.forName(name);
                Intent intent = new Intent(currentActivity,toActivity);
                intent.putExtra("msg", params);
                currentActivity.startActivity(intent);
            }
        }catch(Exception e){
            throw new JSApplicationIllegalArgumentException(
                    "不能打開Activity : "+e.getMessage());
        }
    }

2冬竟、JumpRP 聲明了ReactPackage,new了JumpModule民逼,也添加到了MainApplication

public class JumpRP implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(new JumpModule(reactContext));
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

}
如果RN要向原生發(fā)消息泵殴,調用JumpModule里自己定義的方法就行。獻上這個??

可以開始敲代碼了拼苍,在代碼中學習
先來幾個小??吃一吃:先圖再代碼如何笑诅?


image.png
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image
} from 'react-native';

export default class image_demo extends Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    Welcome to React Nativ!
                </Text>
                <Image source={{uri:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1104142377,1692686148&fm=27&gp=0.jpg'}} style={styles.imageStyle} />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
});
image.png
export default class App extends Component{
    render(){
        return(
            <View style={styles.container}>
                <View style={[styles.item,styles.center]}>
                    <Text style={styles.font}>酒店</Text>
                </View>
                <View style={[styles.item,styles.lineLeftRight]}>
                    <View style={[styles.center,styles.flex,styles.lineCenter]}>
                        <Text style={styles.font}>
                            海外酒店
                        </Text>
                    </View>
                    <View style={[styles.center,styles.flex]}>
                        <Text style={styles.font}>
                            特惠酒店
                        </Text>
                    </View>
                </View>
                <View style={styles.item}>
                    <View style={[styles.center,styles.flex,styles.lineCenter]}>
                        <Text style={styles.font}>
                            團購
                        </Text>
                    </View>
                    <View style={[styles.center,styles.flex]}>
                        <Text style={styles.font}>
                            客棧
                        </Text>
                    </View>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        marginTop:20,
        marginLeft:5,
        marginRight:5,
        borderRadius:5,
        padding:2,

        // borderColor:'blue',
        // borderWidth:1,
        flexDirection:'row',
        backgroundColor:'#FF0067'
    },
    item:{
        flex:1,
        height:80
    },
    center:{
        justifyContent:'center',
        alignItems:'center'
    },
    font:{
        color:'#fff',
        fontSize:16,
        fontWeight:'bold'
    },
    flex:{
        flex:1
    },
    lineLeftRight:{
        borderLeftWidth:1,
        borderRightWidth:1,
        borderColor:'#fff'
    },
    lineCenter:{
        borderBottomWidth:1,
        borderColor:'#fff'
    }
});
image.png
var imgs = [   'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1104142377,1692686148&fm=27&gp=0.jpg',
'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1104142377,1692686148&fm=27&gp=0.jpg',
'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1104142377,1692686148&fm=27&gp=0.jpg'
];//需要自己重新賦值鏈接,
class MyImage extends Component{
    constructor(props){
        super(props);
        var imgs=this.props.imgs;
        this.state={
            imgs:imgs,
            count:0,
        }
    }
    goNext(){
        var count = this.state.count;
        count++;
        if(count<imgs.length){
            this.setState({
                count:count,
            })
        }else{
            this.setState({
                count:0,
        })}
    }
    goPreView(){
        var count = this.state.count;
        count--;
        if(count>=0){
            this.setState({
                count:count,
            })
        }else{
            this.setState({
                count:imgs.length-1,
            })
        }
    }
    render(){
        return(
            <View style={[styles.flex]}>
                <View style={styles.image}>
                    <Image style={styles.img} source={{uri:this.state.imgs[this.state.count]}} resizeMode='contain'/>
                </View>
                <View style={styles.btns}>
                    <TouchableOpacity onPress={this.goPreView.bind(this)}>
                        <View style={styles.btn}>
                            <Text>preview</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.goNext.bind(this)}>
                        <View style={styles.btn}>
                            <Text>next</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        )

    }
}

export default class App extends Component{
    render(){
        return(
            <View style={[styles.flex, {marginTop:40}]}>
                <MyImage imgs={imgs}></MyImage>
            </View>
        );
    }
}

var styles = StyleSheet.create({
    flex:{
        flex: 1,
        alignItems:'center'
    },
    image:{
        borderWidth:1,
        width:300,
        height:200,
        borderRadius:5,
        borderColor:'#ccc'
    },
    img:{
        height:200,
        width:300,
    },
    btns:{
        flexDirection: 'row',
        justifyContent: 'center',
        marginTop:20
    },
    btn:{
        width:60,
        height:30,
        borderColor: '#0089FF',
        borderWidth: 1,
        justifyContent: 'center',
        alignItems:'center',
        borderRadius:3,
        marginRight:20,
    },
});

不敲了疮鲫,直接懟開胃??

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末吆你,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子棚点,更是在濱河造成了極大的恐慌,老刑警劉巖湾蔓,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瘫析,死亡現(xiàn)場離奇詭異,居然都是意外死亡默责,警方通過查閱死者的電腦和手機贬循,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來桃序,“玉大人杖虾,你說我怎么就攤上這事∶叫埽” “怎么了奇适?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長芦鳍。 經(jīng)常有香客問我嚷往,道長,這世上最難降的妖魔是什么柠衅? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任皮仁,我火速辦了婚禮,結果婚禮上菲宴,老公的妹妹穿的比我還像新娘贷祈。我一直安慰自己,他們只是感情好喝峦,可當我...
    茶點故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布势誊。 她就那樣靜靜地躺著,像睡著了一般谣蠢。 火紅的嫁衣襯著肌膚如雪键科。 梳的紋絲不亂的頭發(fā)上闻丑,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天,我揣著相機與錄音勋颖,去河邊找鬼嗦嗡。 笑死,一個胖子當著我的面吹牛饭玲,可吹牛的內容都是我干的侥祭。 我是一名探鬼主播,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼茄厘,長吁一口氣:“原來是場噩夢啊……” “哼矮冬!你這毒婦竟也來了?” 一聲冷哼從身側響起次哈,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤胎署,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后窑滞,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體琼牧,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年哀卫,在試婚紗的時候發(fā)現(xiàn)自己被綠了巨坊。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡此改,死狀恐怖趾撵,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情共啃,我是刑警寧澤占调,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站移剪,受9級特大地震影響妈候,放射性物質發(fā)生泄漏。R本人自食惡果不足惜挂滓,卻給世界環(huán)境...
    茶點故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一苦银、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧赶站,春花似錦幔虏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至烙博,卻和暖如春瑟蜈,著一層夾襖步出監(jiān)牢的瞬間烟逊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工铺根, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留宪躯,地道東北人。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓位迂,卻偏偏與公主長得像访雪,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子掂林,可洞房花燭夜當晚...
    茶點故事閱讀 45,870評論 2 361

推薦閱讀更多精彩內容