简体   繁体   中英

How to add a backdrop clickable overlay on official react-native Modal?

This is the official react-native modal documentation and this is a live example for iOS and Android.

How can I add a clickable backdrop overlay which is over my view and under the modal?

You can wrap the Modal content in a Touchable Opacity and style it with a background. I edited the sample given in the documentation.

     <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert('Modal has been closed.');
        }}>
        <TouchableOpacity
          style={{ backgroundColor: 'black', flex: 1,justifyContent:'center' }}
          onPress={() => setModalVisible(!modalVisible)}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello World!</Text>

            <TouchableHighlight
              style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
              onPress={() => {
                setModalVisible(!modalVisible);
              }}>
              <Text style={styles.textStyle}>Hide Modal</Text>
            </TouchableHighlight>
          </View>
        </TouchableOpacity>
      </Modal>

React Native Elements has a fantastic component called Overlay that would solve your problem. It saved me earlier this week. The only issue is that it is part of a larger library.
https://react-native-elements.github.io/react-native-elements/docs/overlay.html

I think if the separation between the backdrop and your modal is not crucial to your project, you can handle it like this:

       <Modal
          animationType="slide"
          transparent={true}
          style={{ width: '100%', alignSelf: 'center', height: '100%', justifyContent: 'flex-start' }}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            // Do smth
          }}>
          <TouchableWithoutFeedback style={{ flex: 1 }} onPress={() => {
            // Do the backdrop action
          }}>
            <View style={{ backgroundColor: '#fff', flex: 1, width: '80%', height: '50%' }} >
              <Text> Your content </Text>
            </View>
          </TouchableWithoutFeedback>
        </Modal>

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