react-native自定义组件

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

直接进入主题,现需自定义一个组件,要求如下

实例,自定义一个Loading组件,也就是常用的等待加载的hud组件

新建一个Loading.js文件
![loading.gif](https://img.haomeiwen.com/i9472084/9bd7eca033c9a7ae.gif?imageMogr2/auto-orient/strip)

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

// create a component
const MyLoading = (props) => {
    return (
        <TouchableOpacity onPress={props.onTap}>
            <View style={styles.container}>
                <ActivityIndicator color={'white'} size={'large'}></ActivityIndicator>
                <Text style={[styles.myText]}>{props.title}</Text>
            </View>

        </TouchableOpacity>
    );
};

// define your styles
const styles = StyleSheet.create({
    container: {
        // flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#a5a5a5',
        height: 100,
        width: 100,
        borderRadius: 10
    },
    myText: {
        color: 'white',
        marginTop: 15
    }
});

//make this component available to the app
export default MyLoading;

外面使用组件
            <MyLoading title="请稍后。。。" onTap={() => {
                console.log("loading... tapped")
            }}></MyLoading>
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import MyLoading from './custom_component/loading'
// create a component
const HomeScreen = ({ navigation }) => {


    goToDetailScreen = () => {
        navigation.navigate('Detail')
    }

    return (
        <View style={styles.container}>
            <Text>HomeScreen</Text>
            <Button title='to detail screen' onPress={goToDetailScreen}></Button>
            <MyLoading title="请稍后。。。" onTap={() => {
                console.log("loading... tapped")
            }}></MyLoading>
        </View>
    );
};

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f5f5f5',
    },
});

//make this component available to the app
export default HomeScreen;

最终效果如下:

loading.gif

结尾

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

上一篇 下一篇

猜你喜欢

热点阅读