React-Native基礎(chǔ)

1.樣式設(shè)置

給每個組件設(shè)置樣式,F(xiàn)lex容器可以參考:http://www.reibang.com/p/f378459e285e

export default class first extends Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={[styles.textStyle,{backgroundColor:'#0F0',flex:2}]}>
                    文本1
                </Text>
                <Text style={[styles.textStyle,{height:30,alignSelf:'flex-end'}]}>
                    文本2
                </Text>
                <Text style={[styles.textStyle,{height:50}]}>
                    文本3
                </Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    //可以定義多個樣式谦炬,給組件使用
    container: {
        //主軸方向
        flexDirection:'row', //默認(rèn)column(列)尿褪,垂直方向咐蚯,row(行)水平方向
        backgroundColor: '#F5FCFF',
        flexWrap:'wrap',  //項(xiàng)目超過一行妖异,換行
        //項(xiàng)目在主軸上的對齊方式
        //justifyContent: 'center',
        //交叉軸的對齊方式
        alignItems:'flex-start'
    },
    textStyle : {
        //width:40, //默認(rèn)的單位dp
        height:30,
        backgroundColor:'#F00',
        flex:1 //項(xiàng)目占父容器的比例
    }
});

2.組件的引入還可以采用這種方式:

var BagView = require('./BagView');
var LoginView = require('./LoginView');

export default class first extends Component {
    render() {
        return <LoginView/>
    }
}

//注冊了組件,才能正確被渲染
AppRegistry.registerComponent('first', () => first);

3.獲取本地json數(shù)據(jù)和引入系統(tǒng)控件:

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

//獲取屏幕的寬度
var Dimensions = require('Dimensions');
var width = Dimensions.get('window').width;
var boxWidth = width / 3;

var JsonData = require('./test.json');

class BagView extends Component{
    renderBags = ()=>{
        return JsonData.data.map((item,i) => {
            return <View key={'wrapper'+i} style={styles.wrapperStyle}>
                <Image source={require('../images/danjianbao.png')} style={styles.imageStyle}></Image>
                <Text>{item.title}</Text>
            </View>
        });
    }
    render(){
        return <View style={styles.container}>
            {this.renderBags()}
        </View>;
    }
}

var styles = StyleSheet.create({
    container:{
        flexDirection:'row',
        flexWrap:'wrap' //換行
    },
    wrapperStyle:{
        flexDirection:'column', //主軸潭苞,垂直方向
        alignItems:'center', //交叉軸肃拜,居中對齊
        width:boxWidth,
        height:100
    },
    imageStyle:{
        width:80,
        height:80
    }
});

module.exports = BagView;

4.TouchableOpacity控件

TouchableOpacity 被點(diǎn)擊之后痴腌,透明度發(fā)生改變

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

//獲取屏幕的寬度
var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;

class LoginView extends Component{
    handlePress = ()=>{
        console.log("press");
    }
    render() {
        return <View style={styles.container}>
    <Image source={require('../images/icon.png')} style={styles.iconStyle}></Image>
        <View style={styles.inputWrapperStyle}>
    <TextInput placeholder="輸入QQ號碼" style={styles.inputStyle}></TextInput>
        </View>
        <View style={styles.inputWrapperStyle}>
    <TextInput placeholder="輸入密碼" style={styles.inputStyle} keyboardType="numeric" secureTextEntry={true}></TextInput>
            </View>
            {/*可以用Button
             TouchableOpacity 被點(diǎn)擊之后,透明度發(fā)生改變
             activeOpacity燃领,被點(diǎn)擊時的透明
             */}
            <TouchableOpacity
        activeOpacity={0.5}
        onPress={this.handlePress}>
    <View style={styles.textWrapperStyle}>
    <Text style={{color:'#fff',flex:1,textAlign:'center',alignSelf:'center'}}>登錄</Text>
        </View>
        </TouchableOpacity>

        </View>;
    }
}


var styles = StyleSheet.create({
    container: {
        flexDirection: 'column', //主軸
        alignItems: 'center' //交叉軸居中對齊
    },
    iconStyle: {
        width: 80,
        height: 80,
        borderRadius: 40,
        borderWidth: 2,
        borderColor: '#FFF',
        marginTop: 50,
        marginBottom: 30
    },
    inputWrapperStyle: {
        flexDirection: 'row'
    },
    inputStyle: {
        flex: 1, //填滿父容器
        textAlign: 'center'
    },
    textWrapperStyle:{
        flexDirection:'row',
        backgroundColor:'#87CEFA',
        marginLeft:15,
        marginRight:15,
        borderRadius:8,
        height:30,
        width:ScreenWidth-30,
        marginTop:20
    }
});

module.exports = LoginView;

5.ScrollView控件

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

var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;

class MyScrollView extends Component {
    renderChilds = ()=> {
        var data = ['red', 'green', 'blue', 'yellow'];
        return data.map((item, i)=> {
            return <View key={`item${i}`} style={{backgroundColor:item,width:ScreenWidth,height:200}}>
                <Text>{i}</Text>
            </View>;
        });
    }

    render() {
        return <ScrollView
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            pagingEnabled={true}>
            {/*子元素*/}
            {this.renderChilds()}
        </ScrollView>;
    }
}

module.exports = MyScrollView;

6.BannerView

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

var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;

var JsonData = require('./test2.json');

//http://www.dongnaoedu.com/jason/
var BaseUrl = 'http://10.0.2.2:8080/react-server/';

class BannerView extends Component {
    constructor(props){
        super(props);
        this.state = {
            currentPage:0
        };
    }

    //渲染圖片列表
    renderChilds = ()=> {
        return JsonData.data.map((item, i)=> {
            return <Image key={`item${i}`} source={{uri:BaseUrl+item.img}} style={styles.imageStyle}></Image>;
        });
    }
    //渲染圓
    renderCircles = ()=>{
        return JsonData.data.map((item, i)=> {
            var style = {};
            //當(dāng)前頁面的的指示器士聪,橘黃色
            if(i === this.state.currentPage){
                style = {color:'orange'};
            }
            return <Text key={`text${i}`} style={[styles.circleStyle,style]}>?</Text>
        });
    }
    //滾動的回調(diào)
    /*handleScroll = (e)=>{
        var x = e.nativeEvent.contentOffset.x;
        if(x % ScreenWidth == 0){
            var currentPage = Math.floor(e.nativeEvent.contentOffset.x / ScreenWidth);
            this.setState({currentPage:currentPage});
            //console.log(currentPage);
        }
    }*/
    handleScroll = (e)=>{
        var x = e.nativeEvent.contentOffset.x;
        var currentPage = Math.floor(e.nativeEvent.contentOffset.x / ScreenWidth);
        this.setState({currentPage:currentPage});
        console.log("currentPage:"+currentPage);
    }

    //定時器
    startTimer = ()=>{
        this.timer = setInterval(()=>{
            //計算出要滾動到的頁面索引,改變state
            var currentPage = ++this.state.currentPage == JsonData.data.length ? 0 : this.state.currentPage;
            this.setState({currentPage:currentPage});
            //計算滾動的距離
            var offsetX = currentPage * ScreenWidth;
            this.refs.scrollView.scrollTo({x:offsetX,y:0,animated:true});
            console.log(currentPage);
        },2000);
    }
    //開始滑動
    handleScrollBegin = ()=>{
        console.log("handleScrollBegin");
        clearInterval(this.timer);
    }

    handleScrollEnd = ()=>{
        console.log("handleScrollEnd");
        this.startTimer();
    }

    render() {
        return <View style={styles.container}>
            {/*注釋不能卸載<>括號里面猛蔽,
             其他的事件:http://blog.csdn.net/liu__520/article/details/53676834
            ViewPager onPageScoll onPageSelected onScroll={this.handleScroll}*/}
            <ScrollView
                ref="scrollView"
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                pagingEnabled={true}                
                onMomentumScrollBegin={this.handleScroll}
                onScrollBeginDrag={this.handleScrollBegin}
                onScrollEndDrag={this.handleScrollEnd}>             
                {/*子元素*/}
                {this.renderChilds()}
            </ScrollView>
            <View style={styles.circleWrapperStyle}>
                {this.renderCircles()}
            </View>
        </View>;
    }

    //定時器
    componentDidMount = ()=>{
        this.startTimer();
    }
    //取消定時器
    componentWillUnmount =() => {
        clearInterval(this.timer);
    }
}

var styles = StyleSheet.create({
    container: {
        flexDirection:'column'
    },
    imageStyle: {
        width: ScreenWidth,
        height: 120
    },
    circleWrapperStyle:{
        flexDirection:'row',
        //absolute“絕對”定位剥悟,參照標(biāo)準(zhǔn)父容器
        //relative “相對”對位,相對于原來的位置
        position:'absolute',
        bottom:0,
        left:10
    },
    circleStyle:{
        fontSize:25,
        color:'#FFF'
    }
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末曼库,一起剝皮案震驚了整個濱河市区岗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌毁枯,老刑警劉巖慈缔,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異后众,居然都是意外死亡胀糜,警方通過查閱死者的電腦和手機(jī)颅拦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門蒂誉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人距帅,你說我怎么就攤上這事右锨。” “怎么了碌秸?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵绍移,是天一觀的道長。 經(jīng)常有香客問我讥电,道長蹂窖,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任恩敌,我火速辦了婚禮瞬测,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己月趟,他們只是感情好灯蝴,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著孝宗,像睡著了一般穷躁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上因妇,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天问潭,我揣著相機(jī)與錄音,去河邊找鬼婚被。 笑死睦授,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的摔寨。 我是一名探鬼主播去枷,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼是复!你這毒婦竟也來了删顶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤淑廊,失蹤者是張志新(化名)和其女友劉穎逗余,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體季惩,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡录粱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了画拾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片啥繁。...
    茶點(diǎn)故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖青抛,靈堂內(nèi)的尸體忽然破棺而出旗闽,到底是詐尸還是另有隱情,我是刑警寧澤蜜另,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布适室,位于F島的核電站,受9級特大地震影響举瑰,放射性物質(zhì)發(fā)生泄漏捣辆。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一此迅、第九天 我趴在偏房一處隱蔽的房頂上張望汽畴。 院中可真熱鬧促煮,春花似錦、人聲如沸整袁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽坐昙。三九已至绳匀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間炸客,已是汗流浹背疾棵。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留痹仙,地道東北人是尔。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像开仰,于是被迫代替她去往敵國和親拟枚。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評論 2 356

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