認(rèn)識(shí)ReactNative

brew install node
安裝完畢查看版本確定是否安裝成功:
npm -v
  • 替換淘寶鏡像
npm config set registry https://registry.npm.taobao.org --global
  • 安裝React Native
npm install -g yarn react-native-cli

安裝完畢查看版本確定是否安裝成功: 
react-native -v
到這一步如果都是成功的, 說(shuō)明你的react-native已經(jīng)安裝成功了
  • 創(chuàng)建項(xiàng)目
react-native init projectName(項(xiàng)目名)
  • 創(chuàng)建成功之后運(yùn)行你的項(xiàng)目就能看見: 說(shuō)明項(xiàng)目已經(jīng)成功運(yùn)行起來(lái)了
啟動(dòng)當(dāng)前服務(wù).png
自定義創(chuàng)建組件的三種方式:
  • 【1】. 通過(guò)ES6的方式添加自定義組件

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


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用隐孽, 就需要使用關(guān)鍵字export default導(dǎo)出
// export default class HelloComponent extends Component {
//     // render()是為了渲染UI層次占调,必須調(diào)用的函數(shù)
//     render() {
//         return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
//     }
// }
自定義組件的調(diào)用集成.png
  • 【2】. 通過(guò)ES5的方式添加自定義組件
調(diào)用方式與ES6方式相同
/*
 * 方式二:ES5
 */
var HelloComponent = React.createClass({
    render() {
        return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
    }
})
// 在ES5中導(dǎo)出需要特別的方式 module.eexport
module.eexport = HelloComponent;
  • 【3】.通過(guò)函數(shù)方式添加自定義組件

/*
 * 方式三:函數(shù)的方式創(chuàng)建組件
 * 無(wú)狀態(tài), 不能使用this
 */
function HelloComponent () {
    return <Text style={{fontSize:20,backgroundColor:'red'}}>hello</Text>
}
module.export = HelloComponent;
  • 傳值
傳遞值過(guò)程.png

接收值過(guò)程.png
React Native 組件的生命周期
  • 組件的生命周期的方法有三個(gè)周期
  1. 調(diào)用render()裝載的過(guò)程
  2. 更新render()的過(guò)程
  3. 卸載的過(guò)程

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


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用佃却, 就需要使用關(guān)鍵字export default導(dǎo)出
export default class LifecycleComponent extends Component {
    // 加載構(gòu)造方法
    constructor(props) {
        super(props)

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

    // 組件即將加載的時(shí)候調(diào)用的函數(shù)
    componentWillMount() {
        console.log('----componentWillMount----')
    }

    // 組件以及加載完成后調(diào)用的函數(shù)
    componentDidMount() {
        console.log('----componentDidMount----')
    }

    // 組件要更新調(diào)用的函數(shù), 接受組件發(fā)送的props信息
    componentWillReceiveProps(nextProps) {
        console.log('----componentWillReceiveProps----')
    }

    // 在接收到新的props信息的調(diào)用的函數(shù)
    shouldComponentUpdate(nextProps, nextState) {
        console.log('----shouldComponentUpdate----')
        // 這里需要返回一個(gè)bool類型
        return true;
    }

    // 組件被調(diào)用之前調(diào)用的函數(shù)
    componentWillUpdate(nextProps, nextState) {
        console.log('----componentWillUpdate----')
    }

    // 組件被移除之前調(diào)用的函數(shù)
    componentWillUnmount() {
        console.log('----componentWillUnmount----')
    }

    // render()是為了渲染UI層次递宅,必須調(diào)用的函數(shù)
    render() {
        console.log('----render----')
        cusCount = 0
        // 使用props.name接受其他類傳遞的值
        return <View>
            <Text style={{fontSize:20,backgroundColor:'red'}}
                  onPress = {()=>{
                      cusCount = cusCount + 1
                      print(cusCount)
                  }}
            >點(diǎn)擊事件響應(yīng)</Text>
            <Text style={{fontSize:20,backgroundColor:'yellow'}}>點(diǎn)擊了{(lán)this.cusCount}</Text>
        </View>
    }
}

  • 變量導(dǎo)出導(dǎo)入
<變量導(dǎo)出: >
import React,{ Component } from 'react';
import {
    StyleSheet,
    Text,
    View
} from 'react-native';
var name = '小明';
var age = '22';
export {name,age};


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用, 就需要使用關(guān)鍵字export default導(dǎo)出
export default class EIComponent extends Component {
    // render()是為了渲染UI層次宋光,必須調(diào)用的函數(shù)
    render() {
        // 使用props.name接受其他類傳遞的值
        return <Text style={{fontSize:20,backgroundColor:'red'}}>hello.{this.props.name}</Text>
    }
}

導(dǎo)出變量調(diào)用方式.png

  • 函數(shù)的調(diào)用方式與變量調(diào)用方式相同
export function sum(a,b) {
    return a + b;
}

  • 自定義屬性Props

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


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用迫淹, 就需要使用關(guān)鍵字export default導(dǎo)出
export default class PropsTest extends Component {

    static defaultProps={ // 自定義屬性
        // name:'小紅',
        // age:16,
        // sex:'男'
    }

    // 檢查屬性的類型、屬性是否正確等铺浇,需要導(dǎo)入react庫(kù)中的PropTypes類
    // import React,{ Component, PropTypes } from 'react';
    static propTypes={
        name:PropTypes.string,
        age:PropTypes.number,
        sex:PropTypes.string.isRequired, // 必須傳值的屬性
    }

    // render()是為了渲染UI層次痢畜,必須調(diào)用的函數(shù)
    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語(yǔ)法直接實(shí)現(xiàn)

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

  • 自定義State

初始化state有兩種方式:
1.在組件的constructor方法中初始化組件
2.在外部直接定義state


import React,{ Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image // 這里要使用Image的組件所以需要導(dǎo)入raect庫(kù)中的Image
} from 'react-native';

    /**
     * 方式一: ES6
     */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用, 就需要使用關(guān)鍵字export default導(dǎo)出
    export default class StateTest extends Component {
    // 創(chuàng)建私有state
    state={
        size:80
    }
    // state 是組件私有的鳍侣, 沒辦法傳遞的
    constructor(props) {
        super(props)
        // 初始化state
        // this.state={
        //     size:80,
        // }
    }

    // render()是為了渲染UI層次丁稀,必須調(diào)用的函數(shù)
    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>
    }
}

  • 自定義類

導(dǎo)出自定義類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
    }
}

調(diào)用自定義類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,
                        })
                    }}
                >點(diǎn)贊大小:{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
    }
});


  • flexDirection使用

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


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用, 就需要使用關(guān)鍵字export default導(dǎo)出
export default class FlexBoxTest extends Component {
    // render()是為了渲染UI層次倚聚,必須調(diào)用的函數(shù)
    render() {
        // 使用props.name接受其他類傳遞的值
        return (
            // flexDirection:'row-reverse' 默認(rèn)是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>
        )
    }
}

  • button的使用

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


/**
 * 方式一: ES6
 */
// 創(chuàng)建class類HelloComponent如果需要其他類調(diào)用二驰, 就需要使用關(guān)鍵字export default導(dǎo)出
export default class TouchableTest extends Component {
    constructor(props) {
        super(props);
        this.state = ({
            count:0,
            text:'',
        })
    }

    // render()是為了渲染UI層次,必須調(diào)用的函數(shù)
    render() {
        // 使用props.name接受其他類傳遞的值
        return <View>

            <TouchableWithoutFeedback
                disabled={this.state.waiting}
                onPress={()=> {
                    this.setState({text:'正在登錄中...',waiting:true})
                    setTimeout(()=>{
                        this.setState({text:'網(wǎng)絡(luò)不流暢',waiting:false})
                    },2000);

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

            <TouchableWithoutFeedback
                // 點(diǎn)擊事件
                onPress={()=> {
                    this.setState({count: this.state.count+1})
                }}
                // 常摁事件
                onLongPress={()=>{
                Alert.alert('提示','確認(rèn)刪除嗎秉沼?',[
                    {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:'觸摸結(jié)束,持續(xù)時(shí)間:'+(new Date().getTime()-this.state.startTime)+'毫秒'})
                }}
            >
                <View style={styles.button}>
                    <Text style={styles.buttonText}>
                        點(diǎn)我
                    </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的使用

這里Image的使用的四種方式:

1.使用靜態(tài)圖片資源
2.使用網(wǎng)絡(luò)圖片資源
3.使用原生圖片資源
4.使用本地文件系統(tǒng)中的資源
5.使用圖片的技巧

  1. 使用靜態(tài)圖片資源

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



export default class ImageTest extends Component {
    // render()是為了渲染UI層次桶雀,必須調(diào)用的函數(shù)
    render() {

        // 使用靜態(tài)圖片資源

        return <View>

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

  1. 使用網(wǎng)絡(luò)圖片資源

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



export default class ImageTest extends Component {
    // render()是為了渲染UI層次矗积,必須調(diào)用的函數(shù)
    render() {

        // 使用靜態(tài)圖片資源

        return <View>

            <Image
                style={{width:200, height:100,borderWidth:1}}
                source={require('./dianzan.png')} // 圖片默認(rèn)的大小是原圖片尺寸的大小
                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'}} // 加載網(wǎng)絡(luò)圖片需要定義好圖片的寬度和高度react-native沒辦法自動(dòng)添加
            />
            </View>
    }
}

  1. 如何使用原生圖片資源

1.在react-native中加載網(wǎng)絡(luò)圖片和加載原生圖片都沒辦法自行渲染, 需要手動(dòng)設(shè)置大小
2.將圖片導(dǎo)入android與iOS項(xiàng)目中


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



export default class ImageTest extends Component {
    // render()是為了渲染UI層次敞咧,必須調(diào)用的函數(shù)
    render() {

        // 使用靜態(tài)圖片資源

        return <View>

            <Image
                style={{width:200, height:100,borderWidth:1}}
                source={require('./dianzan.png')} // 圖片默認(rèn)的大小是原圖片尺寸的大小
                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'}} // 加載網(wǎng)絡(luò)圖片需要定義好圖片的寬度和高度react-native沒辦法自動(dòng)添加
            />
            <Image
                style={{width:100, height:100,borderWidth:1}}
                source={{url:'fenxiang'}} // 加載原生圖片只需要加載原生圖片中圖片的名字
            />
            </View>
    }
}

基礎(chǔ)知識(shí)棘捣, 繼續(xù)關(guān)注中...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市休建,隨后出現(xiàn)的幾起案子乍恐,更是在濱河造成了極大的恐慌评疗,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件茵烈,死亡現(xiàn)場(chǎng)離奇詭異百匆,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)呜投,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門加匈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人仑荐,你說(shuō)我怎么就攤上這事雕拼。” “怎么了粘招?”我有些...
    開封第一講書人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵啥寇,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我洒扎,道長(zhǎng)辑甜,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任逊笆,我火速辦了婚禮栈戳,結(jié)果婚禮上岂傲,老公的妹妹穿的比我還像新娘难裆。我一直安慰自己,他們只是感情好镊掖,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開白布乃戈。 她就那樣靜靜地躺著,像睡著了一般亩进。 火紅的嫁衣襯著肌膚如雪症虑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評(píng)論 1 308
  • 那天归薛,我揣著相機(jī)與錄音谍憔,去河邊找鬼。 笑死主籍,一個(gè)胖子當(dāng)著我的面吹牛习贫,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播千元,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼苫昌,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了幸海?” 一聲冷哼從身側(cè)響起祟身,我...
    開封第一講書人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤奥务,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后袜硫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體氯葬,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年父款,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了溢谤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡憨攒,死狀恐怖世杀,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情肝集,我是刑警寧澤瞻坝,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站杏瞻,受9級(jí)特大地震影響所刀,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜捞挥,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一浮创、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧砌函,春花似錦斩披、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至仍劈,卻和暖如春厕倍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背贩疙。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工讹弯, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人这溅。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓组民,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親芍躏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子邪乍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容