欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ReactNative实现Toast的示例

程序员文章站 2022-08-09 22:15:22
对于android开发工程师来说,toast在熟悉不过了,用它来显示一个提示信息,并自动隐藏。在我们开发rn应用的时候,我门也要实现这样的效果,就一点困难了,倒也不是困难,...

对于android开发工程师来说,toast在熟悉不过了,用它来显示一个提示信息,并自动隐藏。在我们开发rn应用的时候,我门也要实现这样的效果,就一点困难了,倒也不是困难,只是需要我们去适配,rn官方提供了一个api toastandroid,看到这个名字应该猜出,它只能在android中使用,在ios中使用没有效果,所以,我们需要适配或者我们自定义一个,今天的这篇文章就是自定义一个toast使其在android和ios都能运行,并有相同的运行效果。

源码传送门

定义组件

import react, {component} from 'react';
import {
  stylesheet,
  view,
  easing,
  dimensions,
  text,
  animated
} from 'react-native';
import proptypes from 'prop-types';
import toast from "./index";
const {width, height} = dimensions.get("window");
const viewheight = 35;
class toastview extends component {
  static proptypes = {
    message:proptypes.string,
  };
  dismisshandler = null;

  constructor(props) {
    super(props);
    this.state = {
      message: props.message !== undefined ? props.message : ''
    }
  }

  render() {
    return (
      <view style={styles.container} pointerevents='none'>
        <animated.view style={[styles.textcontainer]}><text
          style={styles.defaulttext}>{this.state.message}</text></animated.view>
      </view>
    )
  }
  componentdidmount() {
    this.timingdismiss()
  }

  componentwillunmount() {
    cleartimeout(this.dismisshandler)
  }


  timingdismiss = () => {
    this.dismisshandler = settimeout(() => {
      this.ondismiss()
    }, 1000)
  };

  ondismiss = () => {
    if (this.props.ondismiss) {
      this.props.ondismiss()
    }
  }
}

const styles = stylesheet.create({
  textcontainer: {
    backgroundcolor: 'rgba(0,0,0,.6)',
    borderradius: 8,
    padding: 10,
    bottom:height/8,
    maxwidth: width / 2,
    alignself: "flex-end",
  },
  defaulttext: {
    color: "#fff",
    fontsize: 15,
  },
  container: {
    position: "absolute",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    flexdirection: "row",
    justifycontent: "center",
  }
});
export default toastview

首先导入我们必须的基础组件以及api,我们自定义组件都需要继承它,dimensions用于实现动画,easing用于设置动画的轨迹运行效果,proptypes用于对属性类型进行定义。

render方法是我们定义组件渲染的入口,最外层view使用position为absolute,并设置left,right,top,bottom设置为0,使其占满屏幕,这样使用toast显示期间不让界面监听点击事件。内层view是toast显示的黑框容器,backgroundcolor属性设置rgba形式,颜色为黑色透明度为0.6。并设置圆角以及最大宽度为屏幕宽度的一半。然后就是text组件用于显示具体的提示信息。

我们还看到proptypes用于限定属性message的类型为string。constructor是我们组件的构造方法,有一个props参数,此参数为传递过来的一些属性。需要注意,构造方法中首先要调用super(props),否则报错,在此处,我将传递来的值设置到了state中。

对于toast,显示一会儿自动消失,我们可以通过settimeout实现这个效果,在componentdidmount调用此方法,此处设置时间为1000ms。然后将隐藏毁掉暴露出去。当我们使用settimeout时还需要在组件卸载时清除定时器。组件卸载时回调的时componentwillunmount。所以在此处清除定时器。

实现动画效果

在上面我们实现了toast的效果,但是显示和隐藏都没有过度动画,略显生硬。那么我们加一些平移和透明度的动画,然后对componentdidmount修改实现动画效果

在组件中增加两个变量

moveanim = new animated.value(height / 12);
  opacityanim = new animated.value(0);

在之前内层view的样式中,设置的bottom是height/8。我们此处将view样式设置如下

style={[styles.textcontainer, {bottom: this.moveanim, opacity: this.opacityanim}]}

然后修改componentdidmount

componentdidmount() {
    animated.timing(
      this.moveanim,
      {
        tovalue: height / 8,
        duration: 80,
        easing: easing.ease
      },
    ).start(this.timingdismiss);
    animated.timing(
      this.opacityanim,
      {
        tovalue: 1,
        duration: 100,
        easing: easing.linear
      },
    ).start();
  }

也就是bottom显示时从height/12到height/8移动,时间是80ms,透明度从0到1转变执行时间100ms。在上面我们看到有个easing属性,该属性传的是动画执行的曲线速度,可以自己实现,在easing api中已经有多种不同的效果。大家可以自己去看看实现,源码地址是 https://github.com/facebook/react-native/blob/master/libraries/animated/src/easing.js ,自己实现的话直接给一个计算函数就可以,可以自己去看模仿。

定义显示时间

在前面我们设置toast显示1000ms,我们对显示时间进行自定义,限定类型number,

time: proptypes.number

在构造方法中对时间的处理

time: props.time && props.time < 1500 ? toast.short : toast.long,

在此处我对时间显示处理为short和long两种值了,当然你可以自己处理为想要的效果。

然后只需要修改timingdismiss中的时间1000,写为this.state.time就可以了。

组件更新

当组件已经存在时再次更新属性时,我们需要对此进行处理,更新state中的message和time,并清除定时器,重新定时。

componentwillreceiveprops(nextprops) {
   this.setstate({
      message: nextprops.message !== undefined ? nextprops.message : '',
      time: nextprops.time && nextprops.time < 1500 ? toast.short : toast.long,
    })
    cleartimeout(this.dismisshandler)
    this.timingdismiss()
  }

组件注册

为了我们的定义的组件以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 查看。文中若有不足或错误的地方欢迎指出。希望对大家的学习有所帮助,也希望大家多多支持。最后新年快乐。