直接进入主题,现需自定义一个组件,要求如下
- 能给组件传参数
- 使用组件触发事件后,能回传到组件
实例,自定义一个Loading组件,也就是常用的等待加载的hud组件
新建一个Loading.js文件
- 函数型组件
- 因为外面使用会传参数进来,所以要带props
- 参数有2个,一个是title,组件要显示的文字,另一个是onTap,事件回调方法(可以根据需求传更多参数进来的)

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;
外面使用组件
- 引入组件,
- 使用组件时,传递2个对应的参数title,onTap
            <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和移动端原生开发相关的文章。欢迎在下面留言交流。