在開發rnApp的時候想自己封裝一個自定義的Toast組件,又不想在每個組件文件內單獨引用,於是自己琢磨了一個方法將組件添加到全局。
這里舉例封裝一個自定義的Toast組件,這個文件可以放在自己的公共組件文件夾下
ToastTip.js
/* * @Date: 2020-02-26 17:40:34 * @Description: 自己封裝Toast提示 * @Author: YooHoeh * @LastEditors: YooHoeh * @LastEditTime: 2020-02-28 18:09:17 */
import React, { Component } from "react";
import { StyleSheet, Text, View, Dimensions, Modal } from "react-native";
const windows = Dimensions.get("window");
export default class ToastTip extends Component {
constructor() {
super();
this.state = {
modalVisible: false,
content: undefined
};
}
show(content) {
setTimeout(() => {
this.setModalVisible(false);
}, 1800);
this.setState({
modalVisible: true,
content
});
}
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
render() {
if (!this.state.modalVisible) return <View />;
const { content } = this.state;
return (
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
alert("Modal has been closed.");
}}
>
<View style={styles.container}>
<View style={styles.content}>
<Text style={styles.contentText}>{content}</Text>
</View>
</View>
</Modal>
);
}
}
module.exports = ToastTip;
const styles = StyleSheet.create({
container: {
position: "absolute",
bottom: 50,
width: windows.width,
justifyContent: "center",
alignItems: "center"
},
content: {
borderRadius: 4,
paddingVertical: 4,
paddingHorizontal: 8,
backgroundColor: "#000000cc"
},
contentText: {
color: "#fff",
lineHeight: 17
}
});
然后在項目根目錄下,找到App.js
文件
導入ToastTip
組件,然后在render
生命周期里將組件渲染,這里需要注意:必須將組件作為在頂層容器的第一個子組件,否則可能出現公共組件調用時未渲染。
App.js
import ToastTip from "./components/ToastTip";
……
class App extends Component {
……
render(){
return (<View>
//這里用global而不用this。
//$toastTip可以自己隨意更改,我這里添加$只是為了使用時區別一般變量。
<ToastTip ref={toastTip => global.$toastTip = toastTip}/>
……
</View>)
}
}
使用方法如下
在任意想要調用的文件內,無需另外引入。
xxx.js
class xxx {
xx(){
$toastTip.show('Bingo!')
}
}