React Native - Modal

  • 简述

    在本章中,我们将向您展示如何在 React Native 中使用模态组件。
    现在让我们创建一个新文件:ModalExample.js
    我们将把逻辑放在里面ModalExample. 我们可以通过运行更新初始状态toggleModal.
    通过运行更新初始状态后toggleModal,我们将设置visible属性到我们的模态。当状态改变时,这个道具将被更新。
    onRequestClose对于 Android 设备是必需的。
  • app.js

    
    import React, { Component } from 'react'
    import WebViewExample from './modal_example.js'
    const Home = () => {
       return (
          <WebViewExample/>
       )
    }
    export default Home;
    
  • modal_example.js

    
    import React, { Component } from 'react';
    import { Modal, Text, TouchableHighlight, View, StyleSheet}
    from 'react-native'
    class ModalExample extends Component {
       state = {
          modalVisible: false,
       }
       toggleModal(visible) {
          this.setState({ modalVisible: visible });
       }
       render() {
          return (
             <View style = {styles.container}>
                <Modal animationType = {"slide"} transparent = {false}
                   visible = {this.state.modalVisible}
                   onRequestClose = {() => { console.log("Modal has been closed.") } }>
                   
                   <View style = {styles.modal}>
                      <Text style = {styles.text}>Modal is open!</Text>
                      
                      <TouchableHighlight onPress = {() => {
                         this.toggleModal(!this.state.modalVisible)}}>
                         
                         <Text style = {styles.text}>Close Modal</Text>
                      </TouchableHighlight>
                   </View>
                </Modal>
                
                <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
                   <Text style = {styles.text}>Open Modal</Text>
                </TouchableHighlight>
             </View>
          )
       }
    }
    export default ModalExample
    const styles = StyleSheet.create ({
       container: {
          alignItems: 'center',
          backgroundColor: '#ede3f2',
          padding: 100
       },
       modal: {
          flex: 1,
          alignItems: 'center',
          backgroundColor: '#f7021a',
          padding: 100
       },
       text: {
          color: '#3f2949',
          marginTop: 10
       }
    })
    
    我们的起始屏幕将如下所示 -
    React Native 开放模式
    如果我们单击按钮,模态将打开。
    React Native