React-Native 学习笔记之组件化开发和setState的使用

17-04-19 00:48 字数 941 阅读 4780 已编辑

推荐一个在线react native模拟器,可直接执行rn代码 http://dabbott.github.io/react-native-web-player


学了一个晚上,语法很不熟悉,因为一个setState多了个=(当成成员变量了)排了半天错,下面的代码主要讲rn模块化开发的简单的例子,和属性state及方法setState的使用。

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

const nameList = ['zhangsan','lisi','wangwu','zhaoliu'];
class GoodMorning extends Component{
    static defaultProps = {
        name : 'somebody'
    };
    render(){
        return (
            <Text>good morning,{this.props.name}!</Text>
        )
    }
}

const GoodEvening = (props) => {
    return(
        <Text>good evening,{props.name}!</Text>
    )
};

class shiqidu extends Component{
    state = {
        likes : 0,
    };
    onPress = ()=>{
        const {likes} = this.state;
        const newLikes = likes + 1;
        this.setState({
            likes : newLikes
        });
    };
    render(){
        return(
            <View style={{marginTop:20,backgroundColor:'#D5D5D5'}}>
                <GoodEvening name="luzhaung" />
                {
                    nameList.map((name,index)=>{
                        return <GoodMorning key={index} name={name} />
                    })
                }
                <View style={styles.container}>
                    <TouchableOpacity onPress={this.onPress}>
                        <Image
                            style={styles.images}
                            source={{
                                uri:'https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/js/Thumbnails/like.png?raw=true'
                            }} />
                    </TouchableOpacity>
                    <Text>{this.state.likes}</Text>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'#d5d5d5',
    },
    images:{
        width:65,
        height:65
    }
});
AppRegistry.registerComponent('shiqidu', () => shiqidu);

执行结果 点赞数量在模拟器上没显示,坑。。

0人点赞>
关注 收藏 改进 举报
2 条评论
排序方式 时间 投票
小青年

厉害了我的骚!

Up骚年
[em_13],学学吧。
请登录后发表评论
站长 @ 十七度
文章
380
粉丝
23
喜欢
191
收藏
31
排名 : 1
访问 : 128.55万
私信