Home Tutorial React Native React Native – Bài 16: Modal

React Native – Bài 16: Modal

3 min read
0
129

Trong chương này, chúng ta sẽ học cách sử dụng thành phần modal trong React Native.

Bây giờ tạo một tệp mới: ModalExample.js

Đặt logic bên trong ModalExample . Chúng ta có thể cập nhật trạng thái ban đầu bằng cách chạy toggleModal .

Sau khi cập nhật trạng thái ban đầu bằng cách chạy toggleModal , chúng ta sẽ đặt thuộc tính visible thành phương thức của mình. Chỗ dựa này sẽ được cập nhật khi trạng thái thay đổi.

OnRequestClose là bắt buộc đối với các thiết bị 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
   }
})

Màn hình bắt đầu của chúng ta sẽ như thế này –

React Native Open Modal

Nếu chúng ta nhấp vào nút, phương thức sẽ mở.

Phản ứng phương thức bản địa

Load More Related Articles
Load More By quangvu
Load More In React Native

Check Also

Tự làm web chatGPT đơn giản cho phép dùng nhiều OpenAI key

Trong thời đại công nghệ phát triển như hiện nay, chatbot đang dần trở thành một giải pháp…