對(duì)于Android開發(fā)工程師來(lái)說(shuō)囚巴,Toast在熟悉不過(guò)了,用它來(lái)顯示一個(gè)提示信息友扰,并自動(dòng)隱藏彤叉。在我們開發(fā)RN應(yīng)用的時(shí)候,我門也要實(shí)現(xiàn)這樣的效果村怪,就一點(diǎn)困難了姆坚,倒也不是困難,只是需要我們?nèi)ミm配实愚,RN官方提供了一個(gè)API ToastAndroid,看到這個(gè)名字應(yīng)該猜出,它只能在Android中使用腊敲,在iOS中使用沒有效果击喂,所以,我們需要適配或者我們自定義一個(gè)碰辅,今天的這篇文章就是自定義一個(gè)Toast使其在Android和iOS都能運(yùn)行懂昂,并有相同的運(yùn)行效果。
定義組件
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
首先導(dǎo)入我們必須的基礎(chǔ)組件以及API没宾,我們自定義組件都需要繼承它凌彬,Dimensions
用于實(shí)現(xiàn)動(dòng)畫,Easing
用于設(shè)置動(dòng)畫的軌跡運(yùn)行效果循衰,PropTypes
用于對(duì)屬性類型進(jìn)行定義铲敛。
render
方法是我們定義組件渲染的入口,最外層view
使用position
為absolute
会钝,并設(shè)置left
,right
,top
,bottom
設(shè)置為0伐蒋,使其占滿屏幕,這樣使用Toast顯示期間不讓界面監(jiān)聽點(diǎn)擊事件迁酸。內(nèi)層View
是Toast顯示的黑框容器先鱼,backgroundColor
屬性設(shè)置rgba形式,顏色為黑色透明度為0.6奸鬓。并設(shè)置圓角以及最大寬度為屏幕寬度的一半焙畔。然后就是Text
組件用于顯示具體的提示信息。
我們還看到propTypes
用于限定屬性message
的類型為string
串远。constructor
是我們組件的構(gòu)造方法宏多,有一個(gè)props
參數(shù),此參數(shù)為傳遞過(guò)來(lái)的一些屬性绷落。需要注意,構(gòu)造方法中首先要調(diào)用super(props)
,否則報(bào)錯(cuò)始苇,在此處,我將傳遞來(lái)的值設(shè)置到了state
中催式。
對(duì)于Toast函喉,顯示一會(huì)兒自動(dòng)消失荣月,我們可以通過(guò)setTimeout
實(shí)現(xiàn)這個(gè)效果管呵,在componentDidMount
調(diào)用此方法,此處設(shè)置時(shí)間為1000ms哺窄。然后將隱藏毀掉暴露出去捐下。當(dāng)我們使用setTimeout
時(shí)還需要在組件卸載時(shí)清除定時(shí)器账锹。組件卸載時(shí)回調(diào)的時(shí)componentWillUnmount
坷襟。所以在此處清除定時(shí)器奸柬。
實(shí)現(xiàn)動(dòng)畫效果
在上面我們實(shí)現(xiàn)了Toast的效果婴程,但是顯示和隱藏都沒有過(guò)度動(dòng)畫廓奕,略顯生硬。那么我們加一些平移和透明度的動(dòng)畫档叔,然后對(duì)componentDidMount
修改實(shí)現(xiàn)動(dòng)畫效果
在組件中增加兩個(gè)變量:
moveAnim = new Animated.Value(height / 12);
opacityAnim = new Animated.Value(0);
在之前內(nèi)層view
的樣式中桌粉,設(shè)置的bottom
是height/8
。我們此處將view
樣式設(shè)置如下:
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
顯示時(shí)從height/12
到height/8
移動(dòng)衙四,時(shí)間是80ms铃肯,透明度從0到1轉(zhuǎn)變執(zhí)行時(shí)間100ms。在上面我們看到有個(gè)easing
屬性缘薛,該屬性傳的是動(dòng)畫執(zhí)行的曲線速度,可以自己實(shí)現(xiàn)卡睦,在Easing API中已經(jīng)有多種不同的效果。大家可以自己去看看實(shí)現(xiàn)(源碼地址)
表锻,自己實(shí)現(xiàn)的話直接給一個(gè)計(jì)算函數(shù)就可以恕齐,可以自己去看模仿瞬逊。
定義顯示時(shí)間
在前面我們?cè)O(shè)置Toast顯示1000ms显歧,我們對(duì)顯示時(shí)間進(jìn)行自定義确镊,限定類型number
士骤。
time: PropTypes.number
在構(gòu)造方法中對(duì)時(shí)間的處理
time: props.time && props.time < 1500 ? Toast.SHORT : Toast.LONG
在此處我對(duì)時(shí)間顯示處理為SHORT
和LONG
兩種值了蕾域,當(dāng)然你可以自己處理為想要的效果拷肌。
然后只需要修改timingDismiss
中的時(shí)間1000旨巷,寫為this.state.time
就可以了巨缘。
組件更新
當(dāng)組件已經(jīng)存在時(shí)再次更新屬性時(shí)采呐,我們需要對(duì)此進(jìn)行處理若锁,更新state中
的message
和time
斧吐,并清除定時(shí)器又固,重新定時(shí)。
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()
}
組件注冊(cè)
為了我們的定義的組件以API的形式調(diào)用仰冠,而不是寫在render
方法中娄周,所以我們定義一個(gè)根組件沪停。
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
就是我們定義的根組件,實(shí)現(xiàn)如上木张,通過(guò)AppRegistry.registerComponent
注冊(cè)。
包裝供外部調(diào)用
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中定義兩個(gè)static
變量舷礼,表示顯示的時(shí)間供外部使用。然后提供兩個(gè)static
方法郊闯,方法中調(diào)用RootView
的setView
方法將ToastView
設(shè)置到根view
。
使用
首先導(dǎo)入上面的Toast
团赁,然后通過(guò)下面方法調(diào)用
Toast.show("測(cè)試,我是Toast");
//能設(shè)置顯示時(shí)間的Toast
Toast.show("測(cè)試",Toast.LONG);