ReactNative实现Toast的示例(3)

组件注册

为了我们的定义的组件以API的形式调用,而不是写在render方法中,所以我们定义一个跟组件

import React, {Component} from "react";
import {StyleSheet, AppRegistry, View, Text} from 'react-native';
viewRoot = null;
class RootView extends Component {
  constructor(props) {
    super(props);
    console.log("constructor:setToast")
    viewRoot = this;
    this.state = {
      view: null,
    }
  }

  render() {
    console.log("RootView");
    return (<View style={styles.rootView} pointerEvents="box-none">
      {this.state.view}
    </View>)
  }
  static setView = (view) => {
//此处不能使用this.setState
    viewRoot.setState({view: view})
  };
}

const originRegister = AppRegistry.registerComponent;
AppRegistry.registerComponent = (appKey, component) => {
  return originRegister(appKey, function () {
    const OriginAppComponent = component();
    return class extends Component {

      render() {
        return (
          <View style={styles.container}>
            <OriginAppComponent/>
            <RootView/>
          </View>
        );
      };
    };
  });
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  rootView: {
    position: "absolute",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    flexDirection: "row",
    justifyContent: "center",
  }
});
export default RootView

RootView就是我们定义的根组件,实现如上,通过AppRegistry.registerComponent注册。

包装供外部调用

import React, {
  Component,
} from 'react';
import RootView from '../RootView'
import ToastView from './ToastView'
class Toast {
  static LONG = 2000;
  static SHORT = 1000;

  static show(msg) {
    RootView.setView(<ToastView
      message={msg}
      onDismiss={() => {
        RootView.setView()
      }}/>)
  }

  static show(msg, time) {
    RootView.setView(<ToastView
      message={msg}
      time={time}
      onDismiss={() => {
        RootView.setView()
      }}/>)
  }
}
export default Toast

Toast中定义两个static变量,表示显示的时间供外部使用。然后提供两个static方法,方法中调用RootView的setView方法将ToastView设置到根view。

使用

首先导入上面的Toast,然后通过下面方法调用

Toast.show("测试,我是Toast");
          //能设置显示时间的Toast
          Toast.show("测试",Toast.LONG);

好了文章介绍完毕。如果想看完整代码,可以进我 GitHub 查看。文中若有不足或错误的地方欢迎指出。希望对大家的学习有所帮助,也希望大家多多支持黑区网络。最后新年快乐。