Tạo modal dialog đơn giản trong react native

d52bb1 2024

Code mẫu: 

 

import { Button, Modal, StyleSheet, Text, View } from 'react-native'
import React, { useState } from 'react'

const App = () => {
 const [showDialog, setshowDialog] = useState(false)
 return (
   <View>
     <Text>App</Text>
     <Button title='Mở dialog' onPress={ () => setshowDialog(true)  }/>

     <Modal visible={showDialog}
     >
       <View>
         <View>
           {/* Nội dung dialog viết ở đây */}
           <Text>Nội dung trong Dialog </Text>
           <Button title='Đóng dialog' onPress={ () => setshowDialog(false)  }/>
         </View>
       </View>
     </Modal>


   </View>
 )
}

export default App


const styles = StyleSheet.create({})

Tạo biến trạng thái sử dụng useState để lưu trạng thái hiển thị hoặc ẩn dialog bằng lệnh

const [showDialog, setshowDialog] = useState(false)

Cải tiến tạo định dạng cho dialog

 

import { Button, Modal, StyleSheet, Text, View } from 'react-native'
import React, { useState } from 'react'


const App = () => {
 const [showDialog, setshowDialog] = useState(false)
 return (
   <View>
     <Text>App</Text>
     <Button title='Mở dialog' onPress={ () => setshowDialog(true)  }/>


     <Modal visible={showDialog}
             transparent= {true}
             onRequestClose={ ()=>{
               setshowDialog (false);
             }}
     >
       <View style={st.khung}>
         <View style={st.dialog}>
           {/* Nội dung dialog viết ở đây */}
          
           <Text>Nội dung trong Dialog </Text>
           <Button title='Đóng dialog' onPress={ () => setshowDialog(false)  }/>
         </View>
       </View>
     </Modal>


   </View>
 )
}


export default App


const st = StyleSheet.create({
     khung:{
       flex:1,
       justifyContent: 'center',
       alignItems: 'center',
       backgroundColor: 'rgba(0, 0, 0, 0.6)',// dùng cái này để có nền mờ
     
     },
     dialog:{
       width: 350,
       height:300,
       backgroundColor:'yellow',
       padding: 10,
       borderRadius: 10
     }
})

 

 

 

 

 

Nguồn: zezo.dev