简体   繁体   中英

Back button event listener with react-native-image-zoom-viewer

I'm trying to use the plugin react-native-image-zoom-viewer to display an image preview and I want to achieve the simple goal of closing the modal when the user clicks the Android back button. However, the handler function closeModal is not fired upon clicking.

I already tried to replace closeModal by a non-anonymous function but I still got no results. How could I workaround this problem?

Thanks for help!

import ImageViewer from 'react-native-image-zoom-viewer'
import { BackHandler, Modal } from 'react-native'
import React, { useEffect, useState } from 'react'

const [isModalVisible, setModalVisible] = useState(false)

const closeModal = () => {
  if (isModalVisible) {
    setModalVisible(false)
  }
}

useEffect(() => {
  BackHandler.addEventListener('hardwareBackPress', closeModal)
  return () => BackHandler.removeEventListener('hardwareBackPress', closeModal)
}, [])


// Here is how I call the modal in the jsx
<Modal transparent visible={isModalVisible}>
  <ImageViewer
    enableSwipeDown
    imageUrls={[
      {
        url: picture.url_min,
      },
    ]}
    onSwipeDown={closeModal}
    renderIndicator={() => null}
    saveToLocalByLongPress={false}
  />
</Modal>

hopfully this will work on your project, i just add onRequestClose={} inside Modal

const closeModal = () => { if (isModalVisible) { setModalVisible(false) } }

Modal transparent visible={isModalVisible} onRequestClose={closeModal} >

and put your close function to onRequestClose={}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM