React Native ToastView 工具类(适配Android 与IOS)

前端之家收集整理的这篇文章主要介绍了React Native ToastView 工具类(适配Android 与IOS)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、ToastView

根据属性type来设置不同的Toast的样式

  1. import React,{Component} from 'react';
  2. import {
  3. StyleSheet
  4. } from 'react-native';
  5.  
  6.  
  7. import px2dp from "../utils/Px2Dp";
  8. import Toast,{DURATION} from 'react-native-easy-toast';
  9. import PropTypes from 'prop-types';
  10.  
  11. export default class ToastView extends Component<Props> {
  12.  
  13. static defaultProps = {
  14. type: 'android'
  15. };
  16.  
  17. static propTypes = {
  18. type: PropTypes.oneOf(['android','ios']).isrequired,};
  19.  
  20. constructor(props) {
  21. super(props);
  22. this.state = {
  23. style: '',}
  24. }
  25.  
  26. setStyle = (type) => {
  27. if ('ios' === type) {
  28. return styles.bg_ios;
  29. } else if ('android' === type) {
  30. return styles.bg_android;
  31. }
  32. }
  33. setFontStyle = (type) => {
  34. if ('ios' === type) {
  35. return styles.fontsize_ios;
  36. } else if ('android' === type) {
  37. return styles.fontsize_android;
  38. }
  39. }
  40.  
  41. show = (text) => {
  42. this.refs.toast.show(text)
  43. };
  44. show = (text,duration) => {
  45. this.refs.toast.show(text,duration)
  46. };
  47.  
  48. render() {
  49. const {type} = this.props;
  50. return (
  51. <Toast ref="toast"
  52. style={this.setStyle(type)}
  53. position={'center'}
  54. textStyle={this.setFontStyle(type)}
  55. />
  56.  
  57. );
  58. }
  59. }
  60.  
  61. const styles = StyleSheet.create({
  62. bg_android: {
  63. backgroundColor: '#000000CC',alignItems: 'center',justifyContent: 'center',},bg_ios: {
  64. backgroundColor: 'white',width: px2dp(606),height: px2dp(102),borderRadius: px2dp(8),shadowColor: 'black',shadowOpacity: 0.13,shadowRadius: px2dp(16),shadowOffset: {
  65. width: 0,height: 0,elevation: 0
  66. },fontsize_android: {
  67. color: 'white',fontSize: px2dp(30),fontFamily: 'PingFangSC-Medium',opacity: 0.8,fontsize_ios:{
  68. color: '#3D3D3D',}
  69. });

2、使用

在render()方法的return的View中添加

  1. <ToastView
  2. ref='toast'
  3. type={(Platform.OS === 'ios' ? 'ios' : 'android')}
  4. />

弹出

  1. this.refs.toast.show("密码修改失败,请重试!");

猜你在找的React相关文章