认识ReactNative

2017-11-14  本文已影响18人  劉戦軍
brew install node
安装完毕查看版本确定是否安装成功:
npm -v
npm config set registry https://registry.npm.taobao.org --global
npm install -g yarn react-native-cli

安装完毕查看版本确定是否安装成功: 
react-native -v
到这一步如果都是成功的, 说明你的react-native已经安装成功了
react-native init projectName(项目名)
启动当前服务.png
自定义创建组件的三种方式:

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


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
// export default class HelloComponent extends Component {
//     // render()是为了渲染UI层次,必须调用的函数
//     render() {
//         return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
//     }
// }
自定义组件的调用集成.png
调用方式与ES6方式相同
/*
 * 方式二:ES5
 */
var HelloComponent = React.createClass({
    render() {
        return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
    }
})
// 在ES5中导出需要特别的方式 module.eexport
module.eexport = HelloComponent;

/*
 * 方式三:函数的方式创建组件
 * 无状态, 不能使用this
 */
function HelloComponent () {
    return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
}
module.export = HelloComponent;
传递值过程.png
接收值过程.png
React Native 组件的生命周期
  1. 调用render()装载的过程
  2. 更新render()的过程
  3. 卸载的过程

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


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
export default class LifecycleComponent extends Component {
    // 加载构造方法
    constructor(props) {
        super(props)

        console.log('----constructor----')
    }

    // 组件即将加载的时候调用的函数
    componentWillMount() {
        console.log('----componentWillMount----')
    }

    // 组件以及加载完成后调用的函数
    componentDidMount() {
        console.log('----componentDidMount----')
    }

    // 组件要更新调用的函数, 接受组件发送的props信息
    componentWillReceiveProps(nextProps) {
        console.log('----componentWillReceiveProps----')
    }

    // 在接收到新的props信息的调用的函数
    shouldComponentUpdate(nextProps, nextState) {
        console.log('----shouldComponentUpdate----')
        // 这里需要返回一个bool类型
        return true;
    }

    // 组件被调用之前调用的函数
    componentWillUpdate(nextProps, nextState) {
        console.log('----componentWillUpdate----')
    }

    // 组件被移除之前调用的函数
    componentWillUnmount() {
        console.log('----componentWillUnmount----')
    }

    // render()是为了渲染UI层次,必须调用的函数
    render() {
        console.log('----render----')
        cusCount = 0
        // 使用props.name接受其他类传递的值
        return <View>
            <Text style={{fontSize:20,backgroundColor:'red'}}
                  onPress = {()=>{
                      cusCount = cusCount + 1
                      print(cusCount)
                  }}
            >点击事件响应</Text>
            <Text style={{fontSize:20,backgroundColor:'yellow'}}>点击了{this.cusCount}</Text>
        </View>
    }
}

<变量导出: >
import React,{ Component } from 'react';
import {
    StyleSheet,
    Text,
    View
} from 'react-native';
var name = '小明';
var age = '22';
export {name,age};


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
export default class EIComponent extends Component {
    // render()是为了渲染UI层次,必须调用的函数
    render() {
        // 使用props.name接受其他类传递的值
        return <Text style={{fontSize:20,backgroundColor:'red'}}>hello.{this.props.name}</Text>
    }
}

导出变量调用方式.png
export function sum(a,b) {
    return a + b;
}


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


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
export default class PropsTest extends Component {

    static defaultProps={ // 自定义属性
        // name:'小红',
        // age:16,
        // sex:'男'
    }

    // 检查属性的类型、属性是否正确等,需要导入react库中的PropTypes类
    // import React,{ Component, PropTypes } from 'react';
    static propTypes={
        name:PropTypes.string,
        age:PropTypes.number,
        sex:PropTypes.string.isRequired, // 必须传值的属性
    }

    // render()是为了渲染UI层次,必须调用的函数
    render() {

        // 使用props.name接受其他类传递的值
        return (
            <View>
                <Text style={{fontSize:20,backgroundColor:'red'}}>{this.props.age}</Text>
                <Text style={{fontSize:20,backgroundColor:'red'}}>{this.props.name}</Text> // 这里的props是只读的属性
                <Text style={{fontSize:20,backgroundColor:'red'}}>{this.props.sex}</Text>
            </View>
        )
    }
}

自定义属性延展操作符 能够使用ES6语法直接实现

render() {
    var params = {name:'小足',age:18,sex:'男'};
    return (
      <View style={styles.container}>
        <PropsTest
            {...params} //延展操作符
        />
      </View>
    );
  }

初始化state有两种方式:
1.在组件的constructor方法中初始化组件
2.在外部直接定义state


import React,{ Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image // 这里要使用Image的组件所以需要导入raect库中的Image
} from 'react-native';

    /**
     * 方式一: ES6
     */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
    export default class StateTest extends Component {
    // 创建私有state
    state={
        size:80
    }
    // state 是组件私有的, 没办法传递的
    constructor(props) {
        super(props)
        // 初始化state
        // this.state={
        //     size:80,
        // }
    }

    // render()是为了渲染UI层次,必须调用的函数
    render() {
        // 使用props.name接受其他类传递的值
        return <View>
            <Text
                style={{fontSize:20}}
                onPress={()=>{
                    this.setState({
                        size: this.state.size+20
                    })
                }}
            >👍👍👍👍</Text>
            <Text
                style={{fontSize:20}}
                    onPress={()=>{
                        this.setState({
                        size: this.state.size-10
                    })
                }}
            >不赞不赞不赞不赞</Text>
            
            <Image
                style={{width: this.state.size, height: this.state.size}}
                source={require('./dianzan.png')}
    />
        </View>
    }
}

导出自定义类class

export default class Student {
    constructor(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    getDescription() {
        return '姓名:' + this.name + '   年龄:'+ this.age + '   性别:' + this.sex
    }
}

调用自定义类classs

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

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

import RefTest from './RefTest'
import Student from './Student'

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<{}> {

    constructor(props) {
        super(props);
        this.state=({
            result:'',
            size:0
        })
        this.stu = new Student('小兰', '20', '女')
    }

    render() {

        var params = {name:'小足',age:18,sex:'男'};

        return (
            <View style={styles.container}>
                <Text
                    style={{fontSize:20}}
                    onPress={()=>{
                        var size = this.refs.reftest.getSize();
                        this.setState({
                            size:size,
                        })
                    }}
                >点赞大小:{this.state.size}</Text>

                <RefTest
                    ref="reftest"
                />
                <Text style={{fontSize:20}}>{this.stu.getDescription()}</Text>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#f1f1f1',
        marginTop:50
    }
});



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


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
export default class FlexBoxTest extends Component {
    // render()是为了渲染UI层次,必须调用的函数
    render() {
        // 使用props.name接受其他类传递的值
        return (
            // flexDirection:'row-reverse' 默认是cloumn
            <View style={ {backgroundColor:"darkgray",marginTop:20}}>
                <View style={ {width:40,height:40,backgroundColor:"darkcyan",margin:5}}>
                    <Text style={ {fontSize:16}}>1</Text>
                </View>
                <View style={ {width:40,height:40,backgroundColor:"darkcyan",margin:5}}>
                    <Text style={ {fontSize:16}}>2</Text>
                </View>
                <View style={ {width:40,height:40,backgroundColor:"darkcyan",margin:5}}>
                    <Text style={ {fontSize:16}}>3</Text>
                </View>
                <View style={ {width:40,height:40,backgroundColor:"darkcyan",margin:5}}>
                    <Text style={ {fontSize:16}}>4</Text>
                </View>
            </View>
        )
    }
}


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


/**
 * 方式一: ES6
 */
// 创建class类HelloComponent如果需要其他类调用, 就需要使用关键字export default导出
export default class TouchableTest extends Component {
    constructor(props) {
        super(props);
        this.state = ({
            count:0,
            text:'',
        })
    }

    // render()是为了渲染UI层次,必须调用的函数
    render() {
        // 使用props.name接受其他类传递的值
        return <View>

            <TouchableWithoutFeedback
                disabled={this.state.waiting}
                onPress={()=> {
                    this.setState({text:'正在登录中...',waiting:true})
                    setTimeout(()=>{
                        this.setState({text:'网络不流畅',waiting:false})
                    },2000);

                }}
            >
                <View style={styles.button}>
                    <Text style={styles.buttonText}>
                        登录
                    </Text>
                </View>
            </TouchableWithoutFeedback>
            <Text style={styles.text}>{this.state.text}</Text>

            <TouchableWithoutFeedback
                // 点击事件
                onPress={()=> {
                    this.setState({count: this.state.count+1})
                }}
                // 常摁事件
                onLongPress={()=>{
                Alert.alert('提示','确认删除吗?',[
                    {text:'取消',onPress:()=>{},style:'cancel'},
                    {text:'确定',onPress:()=>{
                        this.setState({count: this.state.count-1})
                    }}
                ])
            }}
            >
                <View style={styles.button}>
                <Text style={styles.buttonText}>
                    我是TouchableWithoutFeedback,单击我
                </Text>
            </View>
            </TouchableWithoutFeedback>

            <TouchableWithoutFeedback
                onPressIn={()=> {
                    this.setState({text:'触摸开始',startTime:new Date().getTime()})
                }}
                onPressOut={()=>{
                    this.setState({text:'触摸结束,持续时间:'+(new Date().getTime()-this.state.startTime)+'毫秒'})
                }}
            >
                <View style={styles.button}>
                    <Text style={styles.buttonText}>
                        点我
                    </Text>
                </View>
            </TouchableWithoutFeedback>
            <TouchableHighlight
                style= {styles.button}
                activeOpacity={0.7}
                underlayColor='green'
                onHideUnderlay={()=>{
                    this.setState({text:'衬底被隐藏'})
                }}
                onShowUnderlay={()=>{
                    this.setState({text:'衬底显示'})
                }}
                onPress={()=>{

                }}
            >
                <View style={styles.button}>
                    <Text style={styles.buttonText}>
                        TouchableHighlight
                    </Text>
                </View>
            </TouchableHighlight>
            <Text style={styles.text}>{this.state.text}</Text>

            <Text style={styles.text}>{this.state.text}</Text>
            <Text style={styles.text}>您单击了:{this.state.count}次</Text>
        </View>
    }
}

const styles = StyleSheet.create({
    button: {
        borderWidth:1
    },
    buttonText: {
        fontSize:30
},
text: {
    fontSize:20
}
})

这里Image的使用的四种方式:

1.使用静态图片资源
2.使用网络图片资源
3.使用原生图片资源
4.使用本地文件系统中的资源
5.使用图片的技巧

  1. 使用静态图片资源

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



export default class ImageTest extends Component {
    // render()是为了渲染UI层次,必须调用的函数
    render() {

        // 使用静态图片资源

        return <View>

            <Image
                style={{width:200, height:100,borderWidth:1}}
                source={require('./dianzan.png')} // 图片默认的大小是原图片尺寸的大小
                resizeMode={'center'} // 图片的模式: 拉伸、平铺、裁剪等
            />
        </View>
    }
}

  1. 使用网络图片资源

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



export default class ImageTest extends Component {
    // render()是为了渲染UI层次,必须调用的函数
    render() {

        // 使用静态图片资源

        return <View>

            <Image
                style={{width:200, height:100,borderWidth:1}}
                source={require('./dianzan.png')} // 图片默认的大小是原图片尺寸的大小
                resizeMode={'center'}
            />
            <Image
                style={{width:100, height:100,borderWidth:1}}
                source={{url:'http://img4.imgtn.bdimg.com/it/u=1811457400,1412920344&fm=27&gp=0.jpg'}} // 加载网络图片需要定义好图片的宽度和高度react-native没办法自动添加
            />
            </View>
    }
}

  1. 如何使用原生图片资源

1.在react-native中加载网络图片和加载原生图片都没办法自行渲染, 需要手动设置大小
2.将图片导入android与iOS项目中


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



export default class ImageTest extends Component {
    // render()是为了渲染UI层次,必须调用的函数
    render() {

        // 使用静态图片资源

        return <View>

            <Image
                style={{width:200, height:100,borderWidth:1}}
                source={require('./dianzan.png')} // 图片默认的大小是原图片尺寸的大小
                resizeMode={'center'}
            />
            <Image
                style={{width:100, height:100,borderWidth:1}}
                source={{url:'http://img4.imgtn.bdimg.com/it/u=1811457400,1412920344&fm=27&gp=0.jpg'}} // 加载网络图片需要定义好图片的宽度和高度react-native没办法自动添加
            />
            <Image
                style={{width:100, height:100,borderWidth:1}}
                source={{url:'fenxiang'}} // 加载原生图片只需要加载原生图片中图片的名字
            />
            </View>
    }
}

基础知识, 继续关注中...

上一篇下一篇

猜你喜欢

热点阅读