[React Native]從狀態(tài)欄下面滑出Banner(二)

封裝一個(gè)HOC渔彰,方便任意頁(yè)面增加Banner功能

BannerConstants.js

export const BannerStatus = {
  success: 'success',
  warning: 'warning',
  error: 'error',
  info: 'info',
};
export const BannerTimeout = 3000;

ToastBannerComponent

import React from 'react';
import {
  View,
  StyleSheet,
  Text,
  TouchableHighlight,
} from 'react-native';
import PropTypes from 'prop-types';
import svgPath from '../../../../../asserts/SVG/svgPath';
import { BannerStatus } from './BannerConstant';
import SVGImage from '../../../../../common/components/image/SVGImage';

const ToastBannerComponent = (props) => {
  const {
    status, message, actionText, action
  } = props;
  if (!message) {
    return null;
  }
  let bannerColor = 'gray';
  let backgroundColor = 'transparent';
  let path;
  if (status === BannerStatus.success) {
    bannerColor = 'green;
    backgroundColor = '#FEFEFE';
    path = svgPath.SUCCESS_TICK_FILLED;
  } else if (status === BannerStatus.warning) {
    bannerColor = 'yellow';
    backgroundColor =  '#FEFEFE';
    path = svgPath.WARNING_FILLED;
  } else if (status === BannerStatus.error) {
    bannerColor = 'red';
    backgroundColor = 'yellow;
    path = svgPath.ERROR_FILLED;
  }
  return (
    <View style={{
      backgroundColor,
      borderBottomColor: bannerColor,
      borderTopColor: bannerColor,
      borderTopWidth: StyleSheet.hairlineWidth,
      borderBottomWidth: StyleSheet.hairlineWidth,
      justifyContent: 'center',
    }}>
      <View style={{
        flexDirection: 'row',
        justifyContent: 'space-between',
        margin: MarginSize.mini,
      }}>
        {path &&
          (<View style={styles.iconView}>
            <SVGImage
              {...applyTestIdInProps(props, 'banner svg image')}
              path={path}
              color={bannerColor}
            />
          </View>)
        }
        <Text
          style={[styles.message,
          { textAlign: (status === BannerStatus.info) ? 'center' : 'auto' }]}
        >
          {message}
        </Text>
        {actionText && (
          <TouchableHighlight
            accessible
            {...testId('BannerAction-Button')}
            underlayColor='transparent'
            style={{ alignSelf: 'center' }}
            onPress={() => { if (action) { action(status); } }}>
            <Text
              style={styles.actionText}
            >
              {actionText}
            </Text>
          </TouchableHighlight>)
        }
      </View>
    </View>
  );
};

ToastBannerComponent.propTypes = {
  status: PropTypes.string,
  message: PropTypes.string.isRequired,
  actionText: PropTypes.string,
  action: PropTypes.func,
};

ToastBannerComponent.defaultProps = {
  status: BannerStatus.success,
  message: '',
  actionText: undefined,
  action: () => { },
};

const styles = StyleSheet.create({
  iconView: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 30
    height: 30,
    alignContent: 'center',
    alignSelf: 'center'
  },
  message: {
    flex: 1,
    marginHorizontal: 20,
    alignContent: 'center',
    alignSelf: 'center'
  },
  actionText: {
    marginRight: 20,
    color: 'blue',
    alignContent: 'center',
    alignSelf: 'center'
  },
});

export default ToastBannerComponent;

ToastBannerHOC.js

import React from 'react';
import {
  View,
  SafeAreaView,
  StyleSheet,
  Animated,
} from 'react-native';
import { BannerStatus, BannerTimeout } from './BannerConstant';
import ToastBannerComponent from './ToastBanner';

/**
 * Usage: wrap component you already designed.
 * Don't use SafeAreaView in your component, it will added here.
 * And you can pass `safeAreaViewProps` with options
 * `export default withToastBanner(YourComponent);`
 * 
 * showBanner:

this.props.showSuccessBanner('Well Done!');
this.props.showSuccessBanner('Well Done!', 5 * 1000);
this.props.showInfoBanner('Information For You!');
this.props.showInfoBanner('Information For You!', 5 * 1000);
this.props.showWarningBanner('There is a warning!There is a warning!There is a warning!There is v!There is a warning!', 'Fix Warnings', () => {
console.log('Fixed warnings');
this.props.hideBanner();
});
this.props.showWarningBanner('There is a warning!There is a warning!There is a warning!There is v!There is a warning!', 'Fix Warnings', () => {
console.log('Fixed warnings');
this.props.hideBanner();
}, 10 * 1000);
this.props.showErrorBanner('There is an error!There is an error!There is an error!There is an error!There is an error!', 'Resolve', () => {
console.log('Resolved'); this.props.hideBanner();
});
this.props.showErrorBanner('There is an error!There is an error!There is an error!There is an error!There is an error!', 'Resolve', () => {
console.log('Resolved'); this.props.hideBanner();
}, 10 * 1000);

hideBanner:
`this.props.hideBanner();`
Or:
Use a `timeout` to hide banner automatically.
*/

export default function withToastBanner(WrappedComponent, options) {
return class extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      makeBannerBackground: true,
      marginAnimation: new Animated.Value(0),
      message: 'Banner',
      status: BannerStatus.info,
      actionText: '',
      action: undefined,
    };
    this.displayBanner = false;
    this.options = options;
    this.bannerHeight = 0;


  }

  showSuccessBanner = (message, timeout) => {
    // If not set timeout, use a default one to auto hide banner
    this.showBanner({
      status: BannerStatus.success,
      message,
      actionText: undefined,
      action: undefined,
      timeout: timeout || BannerTimeout
    });
  }

  showInfoBanner = (message, timeout) => {
    // If not set timeout, use a default one to auto hide banner
    this.showBanner({
      status: BannerStatus.info,
      message,
      actionText: undefined,
      action: undefined,
      timeout: timeout || BannerTimeout
    });
  }

  showWarningBanner = (
    message,
    actionText,
    action,
    timeout
  ) => {
    // Only if user set timeout, it will auto hide.
    // Otherwise pending until user respond to it.
    this.showBanner({
      status: BannerStatus.warning,
      message,
      actionText,
      action,
      timeout
    });
  }

  showErrorBanner = (
    message,
    actionText,
    action,
    timeout
  ) => {
    // Only if user set timeout, it will auto hide.
    // Otherwise pending until user respond to it.
    this.showBanner({
      status: BannerStatus.error,
      message,
      actionText,
      action,
      timeout
    });
  }

  showBanner = ({
    status,
    message,
    actionText,
    action,
    timeout
  }) => {
    console.log(`showBanner ${message}`);
    this.displayBanner = true;
    this.setState({
      status,
      message,
      actionText,
      action,
    })
    if (timeout && timeout !== 0) {
      this.autoHideBanner(timeout);
    }
  }

  autoHideBanner = (timeout) => {
    console.log(`autoHideBanner timeout at ${timeout}`);
    setTimeout(() => {
      this.hideBanner();
    }, timeout);
  }

  hideBanner = () => {
    console.log('hideBanner');
    if (!this.displayBanner) {
      console.log('Already hidden');
      return;
    }
    this.displayBanner = false;
    this.moveBanner(500, 0 - this.bannerHeight);
    setTimeout(() => {
      this.moveBanner(0, 0);
      this.setState({
        message: '',
        makeBannerBackground: true
      });
    }, 600);
  }

  // private functions
  moveBanner = (duration, marginTop) => {
    console.log(`moveBanner ${duration} ${marginTop}`);
    Animated.timing(
      this.state.marginAnimation, {
      useNativeDriver: false,
      toValue: marginTop,
      duration
    }).start();
  }

  initBanner = () => {
    console.log('initBanner');
    this.moveBanner(0, 0 - this.bannerHeight);
  }

  onBannerLayout = (e) => {
    const bannerHeight = e.nativeEvent.layout.height;
    console.log(`onBannerLayout ${bannerHeight}`);
    if (bannerHeight > 0 && this.displayBanner) {
      console.log(`onBannerLayout 2 ${bannerHeight}`);
      this.bannerHeight = bannerHeight;
      this.initBanner();
      this.setState({
        makeBannerBackground: false
      });
      setTimeout(() => {
        this.moveBanner(500, 0)
      }, 1);
    }
  }

  render() {
    let safeAreaViewProps = null;
    if (this.options) {
      safeAreaViewProps = this.props.safeAreaViewProps;
    }
    return (
      <SafeAreaView
        style={styles.container}
        {...safeAreaViewProps}
      >
        <Animated.View
          style={[{ marginTop: this.state.marginAnimation }]}
        >
          <View style={{ height: '100%' }}>
            {
              this.displayBanner && (
                <View style={{
                  position: this.state.makeBannerBackground ? 'absolute' : 'relative',
                  zIndex: 10,
                  backgroundColor: 'transparent',
                  width: '100%',
                  height: 'auto',
                }}>

                  <View onLayout={this.onBannerLayout}>
                    <ToastBannerComponent
                      status={this.state.status}
                      message={this.state.message}
                      action={this.state.action}
                      actionText={this.state.actionText}
                    />
                  </View>
                </View>
              )
            }
            <View style={{
              zIndex: 11,
              backgroundColor: 'white',
              height: '100%'
            }}>
              <WrappedComponent
                showBanner={this.showBanner}
                showSuccessBanner={this.showSuccessBanner}
                showInfoBanner={this.showInfoBanner}
                showWarningBanner={this.showWarningBanner}
                showErrorBanner={this.showErrorBanner}
                hideBanner={this.hideBanner}
                {...this.props}
              />
            </View>
          </View>
        </Animated.View>
      </SafeAreaView>
    );
  }
};
}

const styles = StyleSheet.create({
container: {
  flex: 1,
  backgroundColor: 'transparent',
},
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末霍狰,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子觅赊,更是在濱河造成了極大的恐慌,老刑警劉巖琼稻,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吮螺,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡帕翻,警方通過(guò)查閱死者的電腦和手機(jī)鸠补,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)嘀掸,“玉大人紫岩,你說(shuō)我怎么就攤上這事〔撬” “怎么了泉蝌?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)揩晴。 經(jīng)常有香客問(wèn)我勋陪,道長(zhǎng),這世上最難降的妖魔是什么硫兰? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任诅愚,我火速辦了婚禮,結(jié)果婚禮上劫映,老公的妹妹穿的比我還像新娘违孝。我一直安慰自己,他們只是感情好苏研,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布等浊。 她就那樣靜靜地躺著,像睡著了一般摹蘑。 火紅的嫁衣襯著肌膚如雪筹燕。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,784評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音撒踪,去河邊找鬼过咬。 笑死,一個(gè)胖子當(dāng)著我的面吹牛制妄,可吹牛的內(nèi)容都是我干的掸绞。 我是一名探鬼主播,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼耕捞,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼衔掸!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起俺抽,我...
    開(kāi)封第一講書(shū)人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤敞映,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后磷斧,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體振愿,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年弛饭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了冕末。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡侣颂,死狀恐怖档桃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情横蜒,我是刑警寧澤胳蛮,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站丛晌,受9級(jí)特大地震影響仅炊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜澎蛛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一抚垄、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谋逻,春花似錦呆馁、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至气堕,卻和暖如春纺腊,著一層夾襖步出監(jiān)牢的瞬間畔咧,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工揖膜, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留誓沸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓壹粟,卻偏偏與公主長(zhǎng)得像拜隧,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子趁仙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容