React-Native基础

1.样式设置

给每个组件设置样式,Flex容器可以参考:http://www.jianshu.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', //默认column(列),垂直方向,row(行)水平方向
        backgroundColor: '#F5FCFF',
        flexWrap:'wrap',  //项目超过一行,换行
        //项目在主轴上的对齐方式
        //justifyContent: 'center',
        //交叉轴的对齐方式
        alignItems:'flex-start'
    },
    textStyle : {
        //width:40, //默认的单位dp
        height:30,
        backgroundColor:'#F00',
        flex:1 //项目占父容器的比例
    }
});

2.组件的引入还可以采用这种方式:

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

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

//注册了组件,才能正确被渲染
AppRegistry.registerComponent('first', () => first);

3.获取本地json数据和引入系统控件:

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 被点击之后,透明度发生改变

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 被点击之后,透明度发生改变
             activeOpacity,被点击时的透明
             */}
            <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 = {};
            //当前页面的的指示器,橘黄色
            if(i === this.state.currentPage){
                style = {color:'orange'};
            }
            return <Text key={`text${i}`} style={[styles.circleStyle,style]}>•</Text>
        });
    }
    //滚动的回调
    /*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“绝对”定位,参照标准父容器
        //relative “相对”对位,相对于原来的位置
        position:'absolute',
        bottom:0,
        left:10
    },
    circleStyle:{
        fontSize:25,
        color:'#FFF'
    }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容