react-native(二)组件、视图、各种请求、调试

2017-08-21 04:24:51 react-native 3466 0

本文所有路径,均依据项目根目录
如果项目已经写了,依旧报错,可以请尝试重启node

组件

组件命名规范:每个单词开头要大写,如

YthLabel  

导出组件,就是通过export方法,向外部暴露你输出的方法,方式有两种,示例如下

js/test_community.js

这是自己随手写的一个类

// 默认模块
export default class TestCommunity{
    getInfo(){
        console.log('你引入了:默认模块TestCommunity的getInfo方法')
    }
}

// 普通模块 => Ssc
export class Ssc{
    getInfo(){
        console.log('你引入了:testOutput类的getInfo方法')
    }
}

// 普通模块 => WxSsc
export class WxSsc{
    getInfo(){
        console.log('你引入了:testOutput类的getInfo方法')
    }
}
js/index.js

现在我引入各个模块

import React, { Component } from 'react'; // RN每个视图文件必须导入的文件
import { // RN中自带模块,需要什么模块就导入什么,请依据官方文档
  Text,
  View 
} from 'react-native';  // 导入默认组件,与非默认组件

// 默认模块不用大括号,默认模块和普通模块之间用逗号隔开
import TestCommunity ,{
  Ssc, // 需要该文件中的哪个普通模块,就引入哪个
  WxSsc
} from './test_community'; // 引入同级目录的下的test_community.js

export default class reactNative extends Component {
  constructor(p){ // 构造函数
    super(p); // 继承父类Component的构造函数  
    // 实例化引入的模块类 => 默认模块 =>调用方法
    let test_1 = new TestCommunity();
    test_1.getInfo();
    // 实例化引入的模块类 => 普通模块 =>调用方法
    let test_2 = new Ssc();
    test_2.getInfo();
    // 实例化引入的模块类 => 普通模块 =>调用方法
    let test_3 = new WxSsc();
    test_3.getInfo();
  }
  // 一旦需要视图的,都需要重写父类中的render方法,像这里一样
  render() {
    return (
      <View style={styles.container}>
        <Text>Welcome to SSC品质生活</Text>
      </View>
    );
  }

  AppRegistry.registerComponent('reactNative', () => reactNative); // 注册要输出的页面,该操作只会出现一次
index.android.js

现在我引入这个即将渲染页面的文件

require('./js/index');

调试

手机,点击菜单键,显示大致如下图

选择 `Debug JS Remotely`
这时,你的浏览器应该会弹出来
然后你 按F12 打开控制台
手机,点击菜单键,选择`Reload`,你应该会看到 ,下面的结果

你引入了:默认模块TestCommunity的getInfo方法
你引入了:默认模块Ssc的getInfo方法
你引入了:默认模块WxSsc的getInfo方法

网络请求

现在我给 `js/test_community.js` 文件中默认模块,增加一个方法,用于请求数据

export default class TestCommunity{
  getInfo(){
    console.log('你引入了:默认模块TestCommunity的getInfo方法')
  }
  // 网络请求 => GET 方式  
  getWebSource(){
    console.log( '正在准备请求链接' ); 
    return fetch('http://www.hlzblog.top/err/error.json') // GET方式 获取Json数据  
      .then((response) => {
        console.log( '请求结束,数据获取成功,正在解析数据为json格式' );
        let data = response.json(); // 解析数据为 json格式
        return data; // 传递数据给下一步
      })
      .then((json_data)=>{ // 接收刚刚获取到的数据  
        console.log("从上一步获取到的数据是:");
        console.log( json_data ); // 已经是json对象了 
      })
      .catch((error) => { // 从fetch开始,到最后一个then,有错误出现,则会捕捉错误。
        console.log("出问题了,问题如下:");
        console.error(error);
      });
  }
  // 网络请求 => POST 方式  
  postWebSource(){
    console.log( '正在准备POST请求链接' ); 
    return fetch('http://www.hlzblog.top/Api?con=Common_behaviour&act=user_behaviour_add',{  
        method: 'POST', 
        headers:{
          'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'  
        },  
        body: 'url=http://www.hlzblog.top/Article.html?id=35'  
      }) // POST方式 获取Json数据  
      .then((response) => {  
        console.log( '请求结束,数据获取成功,正在解析数据为json格式' );  
        let data = response.json(); // 解析数据为 json格式  
        return data; // 传递数据给下一步  
      })  
      .then((json_data)=>{ // 接收刚刚获取到的数据   
        console.log("从上一步获取到的数据是:");  
        console.log( json_data ); // 已经是json对象了  
      })  
      .catch((error) => { // 从fetch开始,到最后一个then,有错误出现,则会捕捉错误。  
        console.log("出问题了,问题如下:");  
        console.error(error);  
      });
  } 
}

在 `js/index.js` 的构造函数中的调用该getWebSource方法

    let test_1 = new TestCommunity();
    test_1.getWebSource();

注:POST请求,需要自己加上对应的headers。GET请求,只能用链接直接访问

GET 请求结果如下图

同理,POST请求如下

视图

渲染运用 JSX 语法
通过继承 Component 类,重写render()方法,实现视图输出

props

一个标签上的所有属性,都在这个对象上,是静态的,值是固定的。

渲染前
<View>
  <ythBlog  data-name="云天河" />
</View>

`ythBlog`是一个 Component,如下

import React, { Component } from 'react';
import {
  Text
} from 'react-native';
class ythBlog extends Component{
  render(){
    return (
      <Text>{this.props.data-name}</Text>
    );
  }
}
渲染后
<View>
  <Text>云天河</Text>
</View>

state

通常 在构造函数里面 初始化 `state`

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

export default class Blink extends Component {
  constructor(props) {
    super(props); // 继承父类构造函数
    this.state = {
      if_show: true
    };
    // 定时操作 => 隐藏/显示  
    setInterval(() => {
      // 调用内置方法setState改变它 
      this.setState(previousState => {
        return { 
          if_show: !previousState.if_show 
        };
      });
    }, 1000);
  }

  render() {
    let display = this.state.if_show ? this.props.text : ' '; // 依据状态,判断是否显示  
    return (
      <Text>{display}</Text>
    );
  }
}

后面通过 `setState`方法改变它
它会重新渲染自己这个组件

js/index.js

输出测试

import React, { Component } from 'react';  // 导入默认组件,与非默认组件
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import Blink from './test_state';

export default class reactNative extends Component {
  render() {
    return (
      <View>
        <Text>Welcome to SSC</Text>
        <Blink text='Blink - SSC品质生活' />
      </View>
    );
  }
}

AppRegistry.registerComponent('reactNative', () => reactNative);

Flex布局

详细介绍

实战布局

图片资源

`require` 方式加载,图片将会被打包进App,图片尽量与js同目录
<Image source={require('./imgs/test.png')} />  
`uri` 方式加载,从网络上拉取图片,要求必须设置图片的高、宽
<Image 
  source={{uri:'http://facebook.github.io/react-native/img/header_logo.png'}} 
  style={{width:120,height:200}
}/>
设置加载图片的模式,通过给style里基于属性,如下

cover 模式只求在显示比例不失真的情况下填充整个显示区域

可以对图片进行放大或者缩小,超出显示区域的部分不显示

contain 模式是要求显示整张图片, 可以对它进行等比缩小

图片会显示完整,可能会露出Image控件的底色。 如果图片宽高都小于控件宽高,则不会对图片进行放大

stretch 模式不考虑保持图片原来的宽,高比.填充整个Image定义的显示区域

这种模式显示的图片可能会畸形和失真

<Image 
  source={{uri:'http://facebook.github.io/react-native/img/header_logo.png'}} 
  style={{width:120,height:200,resizeMode:Image.resizeMode.cover}}
/>
<Image 
  source={{uri:'http://facebook.github.io/react-native/img/header_logo.png'}} 
  style={{width:120,height:200,resizeMode:Image.resizeMode.contain}}
/>
<Image 
  source={{uri:'http://facebook.github.io/react-native/img/header_logo.png}} 
  style={{width:120,height:200,resizeMode:Image.resizeMode.stretch}}
/>
注:若无特殊说明,文章均为云天河原创,请尊重作者劳动成果,转载前请一定要注明出处