React-Native 组件之 Modal

前端之家收集整理的这篇文章主要介绍了React-Native 组件之 Modal前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Modal组件可以用来覆盖包含React Native根视图的原生视图(如UIViewController,Activity),用它可以实现遮罩的效果

属性

Modal提供的属性有:

animationType(动画类型) PropTypes.oneOf([‘none’,‘slide’,‘fade’]

  • none:没有动画
  • slide:从底部滑入
  • fade:淡入视野

onRequestClose(被销毁时会调用函数

onShow(模态显示的时候被调用

transparent (透明度) bool

  • 为true时,使用透明背景渲染模态。

visible(可见性) bool

onOrientationChange(方向改变时调用

  • 在模态方向变化时调用,提供的方向只是 ” 或 ”。在初始化渲染的时候也会调用,但是不考虑当前方向。

supportedOrientations(允许模态旋转到任何指定取向)[‘portrait’,‘portrait-upside-down’,‘landscape’,’landscape-left’,’landscape-right’])

  • 在iOS上,模态仍然受 info.plist 中的 UISupportedInterfaceOrientations字段中指定的限制。

示例

Modal的使用非常简单,例如:

  1. <Modal
  2. animationType='slide' //底部滑入
  3. transparent={false} // 不透明
  4. visible={this.state.isModal} // 根据isModal决定是否显示
  5. onRequestClose={() => {this.onRequestClose()}} // android必须实现
  6. >

综合例子:

  1. import React,{ Component} from 'react';
  2. import {
  3. AppRegistry,View,Modal,TouchableOpacity,Text
  4. } from 'react-native';
  5. export default class ModalView extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. modalVisible: false,}
  10. }
  11. setModalVisible = (visible)=> {
  12. this.setState({
  13. modalVisible: visible
  14. })
  15. };
  16. render(){
  17. return(
  18. <View style={{flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#ffaaff'}}>
  19. <Modal animationType={'none'}
  20. transparent={true}
  21. visible={this.state.modalVisible}
  22. onrequestclose={() => {alert("Modal has been closed.")}}
  23. onShow={() => {alert("Modal has been open.")}}
  24. supportedOrientations={['portrait','portrait-upside-down','landscape','landscape-left','landscape-right']}
  25. onOrientationChange={() => {alert("Modal has been OrientationChange.")}}>
  26. <View style={{flex:1,marginTop: 22,backgroundColor: '#aaaaaa',alignItems: 'center'}}>
  27. <View>
  28. <Text>Hello World!</Text>
  29. <TouchableOpacity onPress={() => {
  30. this.setModalVisible(false)
  31. }}>
  32. <Text>隐藏 Modal</Text>
  33. </TouchableOpacity>
  34. </View>
  35. </View>
  36. </Modal>
  37. <TouchableOpacity onPress={() => {
  38. this.setModalVisible(true)
  39. }}>
  40. <Text>显示 Modal</Text>
  41. </TouchableOpacity>
  42. </View>
  43. )
  44. }
  45. }
  46. AppRegistry.registerComponent('ModalView',()=>ModalView);

运行效果

从 modal 的源码可以看出,modal 其实就是使用了 绝对定位,所以当 modal 无法满足我们的需求的时候,我们就可以通过 绝对定位 自己来封装一个 modal

猜你在找的React相关文章