react-native小试牛刀

2023-08-21  本文已影响0人  微风_10a5

当前环境如下

image.png
第一步,新建一个文件,MyFirstPage,待会作为显示的第一页面
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, Alert } from 'react-native';



// create a component
class MyFirstPage extends React.Component {


    constructor(props) {
        super(props)
        this.state = {
            myText: 'mo ren'
        }
    }

    pressBtnClick = () => {
        Alert.alert("pressed me")
        console.log("butpressBtnClickton", this)
        this.setState({
            myText: 'haha'
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <Text >MyFirstPage</Text>
                <Text style={[styles.text, { color: 'blue' }]}>MyFirstPage</Text>
                <Text>MyFirstPage</Text>
                <Button title='tap me' onPress={() => {
                    console.log('tap me button')
                    Alert.alert("tap me")
                }}
                ></Button>


                <Button title={this.state.myText} onPress={this.pressBtnClick}></Button>
            </View>
        );
    }

}



// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    text: {
        fontSize: 30,
        color: 'red'
    }
});

//make this component available to the app
export default MyFirstPage;
第二步:在index.js文件,替换一下app.js, 如下:
image.png
第三步:在终端,用以下命令,把项目跑起来
yarn ios
//npm run ios
//react-native run-ios

达到的目的有
1.使用基本组件,View, Text, StyleSheet, Button, Alert
2.定义初始值,

this.setState({
            myText: 'haha'
        });

3.点击按钮,触发动作,从而改变初始值,并在界面上显示出来

   pressBtnClick = () => {
        Alert.alert("pressed me")
        console.log("butpressBtnClickton", this)
        this.setState({
            myText: 'haha'
        });
    }

4.熟悉使用 箭头函数

最终效果如下:


rn01.gif

结尾

RN 的分享就到这里喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点个赞加关注吧~~ 后续分享更多有关RN Flutter和移动端原生开发相关的文章。欢迎在下面留言交流。

上一篇 下一篇

猜你喜欢

热点阅读