美文网首页速战react-native
react-native开发基础入门

react-native开发基础入门

作者: Yochi | 来源:发表于2017-11-09 11:53 被阅读35次

react-native是面向组件的开发,基础知识相对简单,我们只需先迅速掌握主干知识,在以后的开发中就有了开枝散叶的资本。

项目结构

  • 面向组件的开发,初始化工程内容结构
/**************组件导入**************/ 
import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Image,
    ImageBackground,
} from 'react-native';

/**************平台区分 ios 和 android**************/ 
const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {

/************渲染 相当于viewDidload**************/
  render() {
/**返回显示的内容**/
    return (
      <View style={styles.container}>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

/************布局样式************/
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },

  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

  • 工程目录介绍,新版入口已经统一在index.js里面了


    image.png
    • GitHub如何运行
    $npm install
    $react-native run-ios /react-native run-andriod
    
  • 平常开发目录结构

.
├── andoird/    
├── ios/    
├── src/    // 项目页面
│   ├── index.js        // 注册原生应用入口
│   ├── App.js          // 首页
│   ├── components/     // 各类组件
│   ├── pages/          // 页面
│   ├── images/         // 图片
│   ├── config/         // 项目配置内容
│   ├── logic/          // 项目逻辑
│   └── utils/          // 项目共计
└── network             // 网络服务
    └── DataService.js
.
├── components    //组成应用的各个组件
│   ├── Routers.android.js     //每个组件若实现不一样,分为android的实现和ios的实现。
│   ├── Routers.ios.js
│   ├── common       //公共组件
│   ├── issues       //议题页面
│   ├── navigation   //导航组件,android用侧边栏,ios准备用tab
│   └── project      //项目页面
└── network          //网络服务
    └── DataService.js
根据项目具体内容调节。。。

调试

  • 模拟器调试
    • 数据刷新 iOS模拟器 command+R 刷新,command+D呼出操作菜单
      Android模拟器 RR刷新数据,点击右侧菜单按钮呼出菜单
  • 真机调试(电脑和手机设备在同一个Wifi网络环境下)
    • iOS
      • 配置电脑的IP地址
        找到 RCTWebSocketExecutor.m 里面的 localhost 设置为你的电脑的IP地址
      • 修改Bundle ID : 不改很有可能报错!
      • Test 的Team也需要设置
      • 手机摇一摇呼出操作菜单
    • Android
      • 在开发者选项里打开USB调试
      • 在cmd命令行或Cygwin输入adb devices就可以看到设备已连接
      • 运行RN项目时,手机和电脑USB连接并且电脑和手机设备在同一个Wifi网络环境下
      • 手机摇一摇呼出操作菜单

布局和样式 (示例工程在末尾)

  • 弹性(Flex)宽高

    • 最简单的给组件设定尺寸的方式就是在样式中指定固定的widthheight。React Native中的尺寸都是无单位的,表示的是与设备像素密度无关的逻辑像素点。(像素、物理像素、逻辑像素的关系看这里
    • 在组件样式中使用flex可以使其在可利用的空间中动态地扩张或收缩。一般而言我们会使用flex:1来指定某个组件扩张以撑满所有剩余的空间。如果有多个并列的子组件使用了flex:1,则这些子组件会平分父容器中剩余的空间。如果这些并列的子组件的flex值不一样,则谁的值更大,谁占据剩余空间的比例就更大(即占据剩余空间的比等于并列组件间flex值的比)。
    • 组件能够撑满剩余空间的前提是其父容器的尺寸不为零。如果父容器既没有固定的width和height,也没有设定flex,则父容器的尺寸为零。其子组件如果使用了flex,也是无法显示的。
  • Flexbox布局

    • Flex Direction
      在组件的style中指定flexDirection可以决定布局的主轴。子元素是应该沿着水平轴(row)方向排列,还是沿着竖直轴(column)方向排列呢?默认值是竖直轴(column)方向。



    • Justify Content

      在组件的style中指定justifyContent可以决定其子元素沿着主轴的排列方式。子元素是应该靠近主轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end、space-around以及space-between。
    • Align Items
      在组件的style中指定alignItems可以决定其子元素沿着次轴(与主轴垂直的轴,比如若主轴方向为row,则次轴方向为column)的排列方式。子元素是应该靠近次轴的起始端还是末尾段分布呢?亦或应该均匀分布?对应的这些可选项有:flex-start、center、flex-end以及stretch。

      注意:要使stretch选项生效的话,子元素在次轴方向上不能有固定的尺寸。
  • 界面样式

/*******************内联************************/
<View style={{flex: 1, backgroundColor: 'powderblue'}} />

/*******************外联************************/
<View style={styles.MyStyle}>
    <Text style={styles.instructions}>
       flexbox我是第一个View
    </Text>
</View>

// 样式定义
const styles = StyleSheet.create({

   instructions: {
     textAlign: 'center',
     color: '#333333',
     marginBottom: 5,
   },// 不同样式间逗号隔开
   MyStyle:{
       flex:1,
       backgroundColor:'red',
       flexDirection:'row', //主轴方向
       justifyContent:'space-around',// 主轴方向的对齐方式
       alignItems:'flex-end',// 次轴方向的对齐方式
   }
});

编写各式各样的UI

  • 静态界面
    TextImageViewprops
  • 登录界面实战练习(见下面示例工程)
  • 动态界面
    要学习如何动态修改你的界面,那就需要进一步
    学习State(状态)的概念

分辨率

// 获取屏幕宽高分辨率
var Dimensions = require('Dimensions');
let screenwidth  = Dimensions.get('window').width;
let screenheight = Dimensions.get('window').height;
let screenheight = Dimensions.get('window').scale;

iOS和Android区分

React Native提供了一个Platform模块用于检测当前运行app的平台。你可以根据这个检测逻辑去应用对应的针对特定平台的代码。

  • Platform.OS
    如果一个组件中只有一小部分代码是针对特定平台的,可以使用这种方式。
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  height: (Platform.OS === 'ios') ? 200 : 100,
});
  • Platform.select(Platform.select方法的key(ios、android)对应的value可以是任意的value)
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});
const Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid'),
})();

// 直接使用
<Component />;
  • 针对特定平台的文件扩展名
    • 如果你针对特定平台的代码比较复杂的话,你应该考虑将它们拆分到独立的文件中。
    • 当一个组件要加载的另外一个组件对应的文件名有
      .ios..android.
      扩展名时React Native会根据当前所处平台来加载对应的文件。
    • 比如说,如果你的项目中有以下两个文件:
      BigButton.ios.js
      BigButton.android.js
      然后你可以用下面这种方式去引入组件:
      const BigButton = require('./BigButton');
      这样子,React Native就会根据当前运行app的平台来自动加载对应的文件了。

react-native生命周期

export default class Test extends Component {
    state={
        title:'默认值',
        person:'Hank'
    }
    static defaultProps={
        age:18
    }
    //
    render() {
        return (
            <View ref="topView" style={styles.container}>
                <Text>{this.state.person}</Text>
                <Text>{this.props.age}</Text>
                <Button title="我就是个Button"
                        color="red"
                        onPress={()=>this.click('点击')}
                />
            </View>
        );
    }
    click(event){
        //
        this.setState({
            title:event
        });
        //拿到View
        console.log(this.refs.topView)
    }
        //相当于OC中的ViewWillAppear
    componentWillMount(){
        //AlertIOS.alert('WillMount来了')
    }
    
    //哥么Render之后 -- 今后用来发送网络请求(第一次加载的数据)
    componentDidMount(){
        // AlertIOS.alert('DidMount')
    }

    //这个方法!!刷新UI之后调用!!!第一次加载UI不会来!!
    componentDidUpdate(){
        AlertIOS.alert('DidUpdate');
    }

    componentWillUnmount() {
        // 卸载界面
    }
    
    //当组件传入的 props 发生变化时调用,例如:父组件状态改变,给子组件传入了新的prop值。用于组件 props 变化后,更新state。
    componentWillReceiveProps(nextProps) {
    
    }
}
const btnClick = ()=>{
    AlertIOS.alert('哥么我来了!!')
}

示例Demo
运行方式:$npm install $react-native run-ios

相关文章

网友评论

    本文标题:react-native开发基础入门

    本文链接:https://www.haomeiwen.com/subject/grulmxtx.html