搞懂这几步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{
    //初始化函数
    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,
                    //将此方法作为参数传到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要向原生发消息,调用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,
    },
});

不敲了,直接怼开胃🌰

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容