React Native添加自定义全局组件

心已赠人 2023-07-09 10:29 74阅读 0赞

在开发rnApp的时候想自己封装一个自定义的Toast组件,又不想在每个组件文件内单独引用,于是自己琢磨了一个方法将组件添加到全局。

这里举例封装一个自定义的Toast组件,这个文件可以放在自己的公共组件文件夹下

ToastTip.js

  1. /* * @Date: 2020-02-26 17:40:34 * @Description: 自己封装Toast提示 * @Author: YooHoeh * @LastEditors: YooHoeh * @LastEditTime: 2020-02-28 18:09:17 */
  2. import React, { Component } from "react";
  3. import { StyleSheet, Text, View, Dimensions, Modal } from "react-native";
  4. const windows = Dimensions.get("window");
  5. export default class ToastTip extends Component {
  6. constructor() {
  7. super();
  8. this.state = {
  9. modalVisible: false,
  10. content: undefined
  11. };
  12. }
  13. show(content) {
  14. setTimeout(() => {
  15. this.setModalVisible(false);
  16. }, 1800);
  17. this.setState({
  18. modalVisible: true,
  19. content
  20. });
  21. }
  22. setModalVisible(visible) {
  23. this.setState({ modalVisible: visible });
  24. }
  25. render() {
  26. if (!this.state.modalVisible) return <View />;
  27. const { content } = this.state;
  28. return (
  29. <Modal
  30. animationType="slide"
  31. transparent={ true}
  32. visible={ this.state.modalVisible}
  33. onRequestClose={ () => {
  34. alert("Modal has been closed.");
  35. }}
  36. >
  37. <View style={ styles.container}>
  38. <View style={ styles.content}>
  39. <Text style={ styles.contentText}>{ content}</Text>
  40. </View>
  41. </View>
  42. </Modal>
  43. );
  44. }
  45. }
  46. module.exports = ToastTip;
  47. const styles = StyleSheet.create({
  48. container: {
  49. position: "absolute",
  50. bottom: 50,
  51. width: windows.width,
  52. justifyContent: "center",
  53. alignItems: "center"
  54. },
  55. content: {
  56. borderRadius: 4,
  57. paddingVertical: 4,
  58. paddingHorizontal: 8,
  59. backgroundColor: "#000000cc"
  60. },
  61. contentText: {
  62. color: "#fff",
  63. lineHeight: 17
  64. }
  65. });

然后在项目根目录下,找到App.js文件
导入ToastTip组件,然后在render生命周期里将组件渲染,这里需要注意:必须将组件作为在顶层容器的第一个子组件,否则可能出现公共组件调用时未渲染。

App.js

  1. import ToastTip from "./components/ToastTip";
  2. ……
  3. class App extends Component {
  4. ……
  5. render(){
  6. return (<View>
  7. //这里用global而不用this。
  8. //$toastTip可以自己随意更改,我这里添加$只是为了使用时区别一般变量。
  9. <ToastTip ref={ toastTip => global.$toastTip = toastTip}/>
  10. ……
  11. </View>)
  12. }
  13. }

使用方法如下
在任意想要调用的文件内,无需另外引入。

xxx.js

  1. class xxx {
  2. xx(){
  3. $toastTip.show('Bingo!')
  4. }
  5. }

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读