React Native之Props&state

2018-09-03  本文已影响7人  谢尔顿

1. Props

import React, {Component} from 'react'

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

class Greeting extends Component{
    render(){
        return (
            <Text>Hello {this.props.name}!</Text>
        );
    }
}
export default class FourthPage extends Component<Props> {
    static navigationOptions = {
        title: 'props',
    };

    render() {
        const {navigate} = this.props.navigation;

        return (
            <View style={styles.container}>
                <Greeting name='RxJava'/>
                <Greeting name='RxAndroid'/>
                <Greeting name='Android'/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f5fcff',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    textView: {
        fontSize: 16,
        textAlign: 'center',
        margin: 10,
        color: 'red'
    }
})

props可以提高自定义组件的复用性。
效果图:


2.state

import React, {Component} from 'react'

import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity
} from 'react-native'

class Blink extends Component{

    constructor(props){
        super(props);
        this.state = {showText:true};
        setInterval(()=>{
            this.setState(previousState => {
                return {showText: !previousState.showText};
            });
        },1000);
    }

    render(){
        let display = this.state.showText ? this.props.text : ' ';
        return(
            <Text>{display}</Text>
        );
    }
}
export default class BlinkApp extends Component<Props> {
    static navigationOptions = {
        // title: 'page 1',
        title: 'state',
    };

    render() {
        return (
            <View style={styles.container}>
                <Blink text='I love to blink'/>
                <Blink text='Yes blinking is so great'/>
                <Blink text='Why did they ever take this out of HTML'/>
                <Blink text='Look at me look at me look at me'/>
            </View>
        );
    }
}

注:setInterval是一个定时器函数,每次调用setState时,BlinkApp都会重新执行render方法重新渲染。

对应的效果图:


上一篇下一篇

猜你喜欢

热点阅读