React-Native基础知识

1. 组件的导入导出

1.1 组件的导出

组件的导出使用关键字export default

/**
*  UIComponent.js文件
*/
import React, { Component } from 'react';
import {View, StyleSheet } from 'react-native';

export default class UIComponent extends Component {
    render() {
        return (
            <View style={styles.content}></View>
        );
    }
}

const styles = StyleSheet.create({
    content: {
        width: 200,
        height: 200,
        backgroundColor: 'orange',
        margin: 50
    }
});

1.2 组件的导入

组件的导入使用import

import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import UIComponent from './UIComponent';

export default class ReactDemo extends Component {
  render() {
    return (
      <UIComponent />
    );
  }
}

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

2. 常量、变量、函数的导入导出

2.1 导出

使用关键字export

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

var name = '张三';
var age = 18;

export { name, age, sum }

export default class UIComponent extends Component {
    render() {
        return (
            <View style={styles.content}></View>
        );
    }
}

const styles = StyleSheet.create({
    content: {
        width: 200,
        height: 200,
        backgroundColor: 'orange',
        margin: 50
    }
});

function sum(x, y) {
    return x + y;
}

2.2 导入

导入使用关键字import

import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import UIComponent, { name, age, sum } from './UIComponent';

export default class ReactDemo extends Component {
  render() {
    return (
      <View>
      <UIComponent />
        <Text style={{fontSize: 24, color: 'blue'}}>姓名: {name}</Text>
        <Text style={{fontSize: 24, color: 'blue'}}>年龄: {age}</Text>
        <Text style={{fontSize: 24, color: 'blue'}}>3 + 2 = {sum(3, 2)}</Text>
      </View>
    );
  }
}

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

3. Props(属性)

大多数组件在创建时就可以使用各种参数来进行定制。用于定制的这些参数就称为props, 只需要在组件中使用this.props即可,Props 是由上个组件传递过来或者本组件定义的默认属性

3.1 上个页面传递过来的属性

/**
*UIComponent.js
*/
import React, { Component } from 'react';
import {View, StyleSheet, Text } from 'react-native';

export default class UIComponent extends Component {
    render() {
        return (
            <View style={styles.content}>
                <Text style={styles.text}>Hello {this.props.name}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    content: {
        width: 200,
        height: 200,
        backgroundColor: 'orange',
        marginTop: 10,
        marginLeft: 50
    },
    text: {
        fontSize: 24,
        color: 'blue'
    }
});

/**
*  入口文件  
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import UIComponent from './UIComponent'

export default class ReactDemo extends Component {
  render() {
    return (
      <View>
        <UIComponent name = "JavaScript"/>
        <UIComponent name = "Objective-C"/>
        <UIComponent name = "Java" />
      </View>
    );
  }
}

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

3.2 定义默认属性

当上一个页面没有传递属性时,使用默认的属性(传递过来的属性优先级高于默认属性),使用关键字static defaultProps

/**
*UIComponent.js
*/
import React, { Component } from 'react';
import {View, StyleSheet, Text } from 'react-native';

export default class UIComponent extends Component {

    static defaultProps = {
        name: 'World'
    }

    render() {
        return (
            <View style={styles.content}>
                <Text style={styles.text}>Hello {this.props.name}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    content: {
        width: 200,
        height: 200,
        backgroundColor: 'orange',
        marginTop: 10,
        marginLeft: 50
    },
    text: {
        fontSize: 24,
        color: 'blue'
    }
});

3.3 属性的类型检查

为了保证类型的正确性,react-native引入了类型检查,使用关键字static propTypes,由于PropTypes是react包中的,所以需要在react包中引入

/**
*UIComponent.js
*/
import React, { Component, PropTypes } from 'react';
import {View, StyleSheet, Text } from 'react-native';

export default class UIComponent extends Component {

    static defaultProps = {
        name: 'World',
    }

    static propTypes = {
        name: PropTypes.string,
        age: PropTypes.number,
        sex: PropTypes.string.isRequired,
    }

    render() {
        return (
            <View style={styles.content}>
                <Text style={styles.text}>姓名: {this.props.name}</Text>
                <Text style={styles.text}>年龄: {this.props.age}</Text>
                <Text style={styles.text}>年龄: {this.props.sex}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    content: {
        width: 200,
        height: 200,
        backgroundColor: 'orange',
        marginTop: 10,
        marginLeft: 50
    },
    text: {
        fontSize: 24,
        color: 'blue'
    }
});

/**
* 入口文件
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import UIComponent from './UIComponent'

export default class ReactDemo extends Component {
  render() {
    var params = {name: '李四', age: 18, sex: '男'};
    return (
      <View>
        <UIComponent {...params}/>
      </View>
    );
  }
}

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

//ES6 解构赋值
/**
* 入口文件
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import UIComponent from './UIComponent'

export default class ReactDemo extends Component {
  render() {
    var params = {name: '李四', age: 18, sex: '男'};
    var {name, sex} = params;
    return (
      <View>
        <UIComponent 
          name={name} 
          sex = {sex}
        />
      </View>
    );
  }
}

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

4. state(状态)

我们使用两种数据来控制组件state、props, props是父组件中指定的,一经指定,在组件的生命周期中不会改变,对于需要改变的数据需要使用state, 通常在constructor中初始化state, 需要改变的时候调用this.setState方法

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

export default class StateTest extends Component {
    constructor(props) {
        super(props);

        this.state = {
            size: 80
        }
    }

        render() {
            return (
                    <Text 
                        style={styles.text} 
                        onPress = {() => {
                                this.setState({
                                    size: this.state.size + 20
                                });
                            }
                        }>{this.state.size}</Text>
                );
            }
}

const styles = StyleSheet.create({
    text: {
        width: 100,
        height: 100,
        fontSize: 30,
        backgroundColor: 'blue',
        color: 'orange',
    }
});

5. ref

ref是组件的一个特殊属性,页面被渲染后指向页面的一个引用。通过这个引用来获取真实的组件。

react-native 中的组件并不是真正的DOM,它是存在于内存中的一种数据结构(虚拟DOM),只有在它插入文档以后才会变成真正的DOM,所有DOM的变动都会发生在虚拟DOM上,再将实际发生变动的部分反映在真正的DOM上,这种算法可以极大的提高页面性能的表现.

/**
*  RefTest.js文件
*/
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';


export default class RefTest extends Component {
    constructor(props)
    {
        super(props);
        this.state = {
            size: 80,
        }
    }

    getSize() {
        return this.state.size;
    }

    render() 
    {
        return (
                <Text 
                    style={styles.text} 
                    // 点击事件
                    onPress = {() => {
                            this.setState({
                                size: this.state.size + 20
                            });
                        }
                    }
                >{this.state.size}</Text>
            );
        }
}

const styles = StyleSheet.create({
    text: {
        width: 200,
        height: 200,
        backgroundColor: 'blue',
        fontSize: 30,
        color: 'white',
        textAlign: 'center',
        lineHeight: 200
    }
});


/**
* 入口文件
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import RefTest from './RefTest'

export default class ReactDemo extends Component {

  constructor(props) 
  {
    super(props);
    this.state = {
      size: 0,
    }
  }

  render() {
     
    return (
      <View>
        <Text 
          style = {{marginTop: 30, fontSize: 50}}
          onPress = {
            () => {
              var size = this.refs.reftest.getSize();
              this.setState({
                size: size,
              });
            }
          }
        >利用ref获取值: {this.state.size}</Text>
        <RefTest
          ref="reftest" />
      </View>
      );
  }
}

思路: 首先为RefTest组件定义了一个ref属性, 当render方法被调用后组件被渲染, 就可以通过this.refs.reftest来获取这个组件的实例,然后通过这个实例来调用这个组件的方法或者变量
注意: 为什么是refs,因为还有其他组件也有这个属性,这里获取的是一个数组。

//类
export default class Student {
    constructor(name, sex, age)
    {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    //定义方法 
    getDescription() 
    {
        return '年龄: ' + this.name + '\n性别:' + this.sex + '\n年龄:' + this.age;
    }
}

/**
* 入口文件
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import Student from './Student'

export default class ReactDemo extends Component {
  constructor()
  {
    super();
    this.stu = new Student('小红', '女', 18);
  }
  render() 
  {
    return(
        <Text
          style={{fontSize: 30, color: 'blue', margin: 50}}
        >{this.stu.getDescription()}</Text>
      );
  }
}

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

6.1 类的继承

import Student from './Student'
export default class MingStudent extends Student {
    constructor(name, sex, age) 
    {
        super(name, sex, age);
    }
    //重构父类方法
    getDescription()
    {
        return super.getDescription();
    }
}

/**
* 入口文件
*/
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View} from 'react-native';
import MingStudent from './MingStudent'

export default class ReactDemo extends Component {
  constructor()
  {
    super();
    this.stu = new MingStudent('小明','男',18);
  }
  render() 
  {
    return(
        <Text
          style={{fontSize: 30, color: 'blue', margin: 50}}
        >{this.stu.getDescription()}</Text>
      );
  }
}

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

推荐阅读更多精彩内容

  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 2,839评论 0 24
  • Hello World react native 官方Hello world示例 我们从import开始来看这个程...
    虫子吃饱了阅读 3,079评论 0 6
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 3,275评论 0 2
  • 我喜欢听鬼讲故事的人却总是讲神其实神和鬼没有什么区别他们一个缤纷一个善良 我喜欢远方讲故事的人却总是离不开院墙其实...
    紫章阅读 314评论 0 3
  • 困顿于生生不息的外表,纠结于丑陋阴暗的挣扎。想奔赴让灵魂和肉体都同步的彼岸,只因生命缺乏勇敢而停滞不前。想要逃离却...
    朴素少年_大美阅读 190评论 0 0