react-native 封装选择弹出框示例(试用ios&android)


Posted in Javascript onJuly 11, 2017

在开发 App 的时候,经常会使用到对话框(又叫消息框、提示框、告警框)。 在web开发中经常会用得到。今天就来介绍了一下react-native 封装弹出框

之前看到react-native-image-picker中自带了一个选择器,可以选择拍照还是图库,但我们的项目中有多处用到这个选择弹出框,所以就自己写了一下,最最重要的是ios和Android通用。先上动态效果图~

react-native 封装选择弹出框示例(试用ios&android)

一、封装要点

1.使用动画实现弹框布局及显示隐藏效果

2.通过一个boolean值控制组件的显示隐藏

3.弹框选项数组通过调用的js传到弹框组件

4.组件选项的字体颜色通过调用js传到组件,实现可拓展;

5.选择选项回调方法

二、代码实现

新建alertSelected.js

/**
 * Created by sybil052 on 2017/6/19.
 */
import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TouchableHighlight,
  Animated,
  Easing,
  Dimensions,
  Platform,
  TouchableOpacity
} from 'react-native';

const {width, height} = Dimensions.get('window');
const [aWidth] = [width-20];
const [left, top] = [0, 0];
const [middleLeft] = [(width - aWidth) / 2];

export default class AlertSelected extends Component {
  constructor(props) {
    super(props);
    this.state = {
      offset: new Animated.Value(0),
      opacity: new Animated.Value(0),
      title: "",
      choose0: "",
      choose1: "",
      hide: true,
      tipTextColor: '#333333',
      aHeight: 236,
    };
    this.entityList = [];//数据源
    this.callback = function () {
    };//回调方法
  }

  render() {
    if (this.state.hide) {
      return (<View />)
    } else {
      return (
        <View style={styles.container}>
          <Animated.View style={styles.mask}>
          </Animated.View>

          <Animated.View style={[{
            width: aWidth,
            height: this.state.aHeight,
            left: middleLeft,
            ...Platform.select({
              ios:{
                bottom: - 20,
              },
            }),
            alignItems: "center",
            justifyContent: "space-between",
          }, {
            transform: [{
              translateY: this.state.offset.interpolate({
                inputRange: [0, 1],
                outputRange: [height, (height - this.state.aHeight - 34)]
              }),
            }]
          }]}>
            <View style={styles.content}>
            <View style={styles.tipTitleView}>
              <Text style={styles.tipTitleText}>{this.state.title}</Text>
            </View>
            {
              this.entityList.map((item, i) => this.renderItem(item, i))
            }
            </View>
            <TouchableHighlight
              style={styles.button}
              underlayColor={'#f0f0f0'}
              onPress={this.cancel.bind(this)}
            >
              <Text style={styles.buttonText}>取消</Text>
            </TouchableHighlight>
          </Animated.View>
        </View>
      );
    }
  }

  renderItem(item, i) {
    return (
      <View style={styles.tipContentView}>
        <View style={{height: 0.5, backgroundColor: '#a9a9a9', width: aWidth}}/>
        <TouchableOpacity
        key={i}
        onPress={this.choose.bind(this, i)}
      >
          <View style={styles.item}>
            <Text style={{
              color: this.state.tipTextColor,
              fontSize: 17,
              textAlign: "center",
            }}>{item}</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }

  componentDidMount() {
  }

  componentWillUnmount() {
    // 如果存在this.timer,则使用clearTimeout清空。
    // 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear
    this.timer && clearTimeout(this.timer);
    this.chooseTimer && clearTimeout(this.chooseTimer);
  }

  //显示动画
  in() {
    Animated.parallel([
      Animated.timing(
        this.state.opacity,
        {
          easing: Easing.linear,//一个用于定义曲线的渐变函数
          duration: 200,//动画持续的时间(单位是毫秒),默认为200。
          toValue: 0.8,//动画的最终值
        }
      ),
      Animated.timing(
        this.state.offset,
        {
          easing: Easing.linear,
          duration: 200,
          toValue: 1,
        }
      )
    ]).start();
 }

  //隐藏动画
  out() {
    Animated.parallel([
      Animated.timing(
        this.state.opacity,
        {
          easing: Easing.linear,
          duration: 200,
          toValue: 0,
        }
      ),
      Animated.timing(
        this.state.offset,
        {
          easing: Easing.linear,
          duration: 200,
          toValue: 0,
        }
      )
    ]).start((finished) => this.setState({hide: true}));
  }

  //取消
  cancel(event) {
    if (!this.state.hide) {
      this.out();
    }
  }

  //选择
  choose(i) {
    if (!this.state.hide) {
      this.out();
      this.chooseTimer = setTimeout(()=>{
        this.callback(i);
      }, 200);
    }
  }

 /**
 * 弹出控件,最多支持3个选项(包括取消)
 * titile: 标题
 * entityList:选择项数据  数组
 * tipTextColor: 字体颜色
 * callback:回调方法
 */
 show(title: string, entityList: Array, tipTextColor: string, callback: Object) {
   this.entityList = entityList;
   this.callback = callback;

   if (this.state.hide) {
     if (entityList && entityList.length > 0) {
       let len = entityList.length;
       if (len === 1) {
         this.setState({title: title, choose0: entityList[0], hide: false, tipTextColor: tipTextColor, aHeight: 180}, this.in);
       } else if (len === 2) {
         this.setState({title: title, choose0: entityList[0], choose1: entityList[1], hide: false, tipTextColor: tipTextColor, aHeight: 236}, this.in);
       }
     }
   }
 }
}

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    width: width,
    height: height,
    left: left,
    top: top,
  },
  mask: {
    justifyContent: "center",
    backgroundColor: "#000000",
    opacity: 0.3,
    position: "absolute",
    width: width,
    height: height,
    left: left,
    top: top,
  },
  // 提示标题
  tipTitleView: {
    height: 56,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
    marginLeft: 10,
    marginRight: 10
  },
  // 提示文字
  tipTitleText: {
    color: "#999999",
    fontSize: 14,
  },
  // 分割线
  tipContentView: {
    width: aWidth,
    height: 56,
    backgroundColor:'#fff',
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
  },
  item:{
    width: aWidth,
    height: 56,
    backgroundColor:'#fff',
    justifyContent: 'center',
    borderRadius: 5,
  },
  button: {
    height: 57,
    backgroundColor: '#fff',
    alignSelf: 'stretch',
    justifyContent: 'center',
    borderRadius: 5,
  },
  // 取消按钮
  buttonText: {
    fontSize: 17,
    color: "#0084ff",
    textAlign: "center",
  },
  content: {
    backgroundColor: '#fff',
    borderRadius: 5,
  }
});

三、使用方法

新建demo.js

const selectedArr = ["拍照", "图库"];
class Demo extends Component {
  constructor(props) {
    super(props);
    this.showAlertSelected = this.showAlertSelected.bind(this);
    this.callbackSelected = this.callbackSelected.bind(this);
  }

  showAlertSelected(){
    this.dialog.show("请选择照片", selectedArr, '#333333', this.callbackSelected);
  }
  // 回调
  callbackSelected(i){
    switch (i){
      case 0: // 拍照
        this.takePhoto();
        break;
      case 1: // 图库
        this.pickMultiple();
        break;
    }
  }
  render() {
    return (
      <View style={stylesCommon.container}>
        <TouchableOpacity onPress={() => {this.showAlertSelected();}}>
          <View style={styles.imageBorder}>
            <Text style={styles.photoText}>?</Text>
          </View>
        </TouchableOpacity>
        <DialogSelected ref={(dialog)=>{
          this.dialog = dialog;
        }} /> 
      </View>
    );
  } 
}

再来一张其他界面调用该组件的效果图~

react-native 封装选择弹出框示例(试用ios&amp;android)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
js如何获取file控件的完整路径具体实现代码
May 15 Javascript
js二维数组排序的简单示例代码
Jan 24 Javascript
解决Jquery鼠标经过不停滑动的问题
Mar 03 Javascript
Vue实现自带的过滤器实例
Mar 09 Javascript
echarts饼图扇区添加点击事件的实例
Oct 16 Javascript
JavaScript数组push方法使用注意事项
Oct 30 Javascript
React Native基础入门之初步使用Flexbox布局
Jul 02 Javascript
React手稿之 React-Saga的详解
Nov 12 Javascript
Bootstrap4 gulp 配置详解
Jan 06 Javascript
微信小程序实现页面跳转传递参数(实体,对象)
Aug 12 Javascript
VUE Elemen-ui之穿梭框使用方法详解
Jan 19 Javascript
JS常用跨域方法实现原理解析
Dec 09 Javascript
vue.js内部自定义指令与全局自定义指令的实现详解(利用directive)
Jul 11 #Javascript
javascript 玩转Date对象(实例讲解)
Jul 11 #Javascript
使用jQuery实现动态添加小广告
Jul 11 #jQuery
Vue中父组件向子组件通信的方法
Jul 11 #Javascript
实例讲解DataTables固定表格宽度(设置横向滚动条)
Jul 11 #Javascript
网页中的图片查看器viewjs使用方法
Jul 11 #Javascript
自定义事件解决重复请求BUG的问题
Jul 11 #Javascript
You might like
php 获取客户端的真实ip
2009/11/30 PHP
基于MySQL体系结构的分析
2013/05/02 PHP
PHP中is_dir()函数使用指南
2015/05/08 PHP
php实现给一张图片加上水印效果
2016/01/02 PHP
php opendir()列出目录下所有文件的实例代码
2016/10/02 PHP
php版微信小店API二次开发及使用示例
2016/11/12 PHP
PHPUnit测试私有属性和方法功能示例
2018/06/12 PHP
setTimeout 不断吐食CPU的问题分析
2009/04/01 Javascript
jquery如何改变html标签的样式(两种实现方法)
2013/01/16 Javascript
jquery文档操作wrap()方法实例简述
2015/01/10 Javascript
简介JavaScript中strike()方法的使用
2015/06/08 Javascript
jquery插件splitScren实现页面分屏切换模板特效
2015/06/16 Javascript
jQuery下拉框的简单应用
2016/06/24 Javascript
canvas绘图不清晰的解决方案
2017/02/28 Javascript
激动人心的 Angular HttpClient的源码解析
2017/07/10 Javascript
JavaScript callback回调函数用法实例分析
2018/05/08 Javascript
nodejs更新package.json中的dependencies依赖到最新版本的方法
2018/10/10 NodeJs
[04:55]完美世界副总裁蔡玮:DOTA2的自由、公平与信任
2013/12/18 DOTA
[00:36]TI7不朽珍藏III——斯温不朽展示
2017/07/15 DOTA
python使用cStringIO实现临时内存文件访问的方法
2015/03/26 Python
Python中使用copy模块实现列表(list)拷贝
2015/04/14 Python
django框架模板中定义变量(set variable in django template)的方法分析
2019/06/24 Python
Django用户认证系统 Web请求中的认证解析
2019/08/02 Python
pycharm中import呈现灰色原因的解决方法
2020/03/04 Python
解决Python 函数声明先后顺序出现的问题
2020/09/02 Python
几款Python编译器比较与推荐(小结)
2020/10/15 Python
python UDF 实现对csv批量md5加密操作
2021/01/01 Python
详解CSS3实现响应式手风琴效果
2020/06/10 HTML / CSS
仿CSDN Blog返回页面顶部功能实现原理及代码
2013/06/30 HTML / CSS
俄罗斯运动鞋商店:Sneakerhead
2018/05/10 全球购物
教育系毕业生中文求职信范文
2013/10/06 职场文书
毕业生怎样写好自荐信
2013/11/11 职场文书
遥感技术与仪器求职信
2014/02/22 职场文书
2014年酒店服务员工作总结
2014/12/08 职场文书
三严三实·严以用权心得体会
2016/01/12 职场文书
游戏《我的世界》澄清Xbox版暂无计划加入光追
2022/04/03 其他游戏