直接進入主題窑睁,現(xiàn)需自定義一個組件褂痰,要求如下
- 能給組件傳參數(shù)
- 使用組件觸發(fā)事件后直晨,能回傳到組件
實例搀军,自定義一個Loading組件,也就是常用的等待加載的hud組件
新建一個Loading.js文件
- 函數(shù)型組件
- 因為外面使用會傳參數(shù)進來勇皇,所以要帶props
- 參數(shù)有2個罩句,一個是title,組件要顯示的文字敛摘,另一個是onTap门烂,事件回調(diào)方法(可以根據(jù)需求傳更多參數(shù)進來的)
![loading.gif](https://upload-images.jianshu.io/upload_images/9472084-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;
外面使用組件
- 引入組件,
- 使用組件時兄淫,傳遞2個對應(yīng)的參數(shù)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;
最終效果如下:
結(jié)尾
RN 的分享就到這里嘍房揭,小伴們,覺得有點用的話备闲,或者已經(jīng)看到這里面來的請點個贊加關(guān)注吧~~ 后續(xù)分享更多有關(guān)RN Flutter和移動端原生開發(fā)相關(guān)的文章。歡迎在下面留言交流捅暴。