繁体   English   中英

通过单击覆盖关闭反应本机模态?

[英]Close react native modal by clicking on overlay?

transparent选项为true时,是否可以通过单击覆盖来关闭反应本机模式 文档没有提供任何相关信息。 可能吗?

如果我理解正确,您想在用户单击其外部时关闭模式,对吗?

如果是的话,我前段时间搜索过这个,我记得的唯一解决方案是这个(这是我迄今为止一直在使用的那个):

render() { 
  if (!this.state.modalVisible)
    return null
  return (
     <View>
        <Modal 
          animationType="fade"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {this.setModalVisible(false)}}
        >
          <TouchableOpacity 
            style={styles.container} 
            activeOpacity={1} 
            onPressOut={() => {this.setModalVisible(false)}}
          >
            <ScrollView 
              directionalLockEnabled={true} 
              contentContainerStyle={styles.scrollModal}
            >
              <TouchableWithoutFeedback>
                <View style={styles.modalContainer}>
                  // Here you put the content of your modal.
                </View>
              </TouchableWithoutFeedback>
            </ScrollView>
          </TouchableOpacity>   
        </Modal> 
     </View>
  )
} 

// Then on setModalVisible(), you do everything that you need to do when closing or opening the modal.
setModalVisible(visible) {
    this.setState({
        modalVisible: visible,
    })
}

解释

这基本上是在整个屏幕中使用 TouchableOpacity 来获取用户单击以关闭模式的时间。 TouchableWithoutFeedback 是为了避免 TouchableOpacity 在 Modal 内部工作。

如果您有更好的解决方案,请在此处分享。

另一种解决方案:

// Modal.js
import React from 'react';
import {
  TouchableWithoutFeedback,
  StyleSheet,
  Modal,
  View,
} from 'react-native';
import t from 'prop-types';


class MyModal extends React.Component {
  static propTypes = {
    children: t.node.isRequired,
    visible: t.bool.isRequired,
    dismiss: t.func.isRequired,
    transparent: t.bool,
    animationType: t.string,
  };

  static defaultProps = {
    animationType: 'none',
    transparent: true,
  };

  render() {
    const { props } = this;
    return (
      <View>
        <Modal
          visible={props.visible}
          transparent={props.transparent}
          onRequestClose={props.dismiss}
          animationType={props.animationType}
        >
          <TouchableWithoutFeedback onPress={props.dismiss}>
            <View style={styles.modalOverlay} />
          </TouchableWithoutFeedback>

          <View style={styles.modalContent}>
            {props.children}
          </View>
        </Modal>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  modalContent: {
    flex: 1,
    justifyContent: 'center',
    margin: '5%',
  },
  modalOverlay: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(0,0,0,0.5)'
  },
});


export default MyModal;

使用示例:

// SomeScreen.js
import React from 'react';
import { View, Text, Button } from 'react-native';

import Modal from './Modal';


class SomeScreen extends React.Component {
  state = {
    isModalVisible: false,
  };

  showModal = () => this.setState({ isModalVisible: true });
  hideModal = () => this.setState({ isModalVisible: false });

  render() {
    return (
      <View>
        <Button onPress={this.showModal} />
        <Modal
          visible={this.state.isModalVisible}
          dismiss={this.hideModal}
        >
          <Text>Hello, I am modal</Text>
        </Modal>
      </View>
    );
  }
}

简单的解决方案。 您需要一个 touchableOpacity 用于在外部单击,另一个 touchableOpacity 用于实际模态,它不会在Press 上执行任何操作。

import React, { Component } from 'react'
import { View, StyleSheet, TouchableOpacity, Modal} from 'react-native';

export class Modal extends Component {
    constructor(props){
        this.state = { modalVisible : true}
    }
    render() {
        return (
            <View>
                <Modal
                    animationType="slide"
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={() => { this.setState({modalVisible: false})
                    }}
                  >
                    <TouchableOpacity style={styles.modalContainer} onPress={() => { this.setState({ modalVisible : false})}}>
                        <TouchableOpacity style={styles.modal} onPress={() => console.log('do nothing')} activeOpacity={1} >
                            Modal Content...
                        </TouchableOpacity>
                    </TouchableOpacity>
                </Modal>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    modalContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    modal: {
      width: 155,
      height: 300
    },
});

export default Modal;

activeOpacity={1} 只是移除 touchableOpacity 淡入淡出效果

我们可以通过添加:

import { TouchableOpacity } from 'react-native';
    <TouchableOpacity onPress={()=>this.setState({modalVisibilty:false})}>
    <View style={{opacity:0, flex:1 }}/>
    </TouchableOpacity>

在窗口下方和另一个上方,并更改布局样式以适合您的屏幕。

解释:

您将制作 2 个大隐藏按钮来捕捉用户触摸并将模态可见性状态更改为 false。

这是我的简单实现:

<TouchableWithoutFeedback onPress={}> // Code to close your modal goes here
    <View style={styles.background}> // The view to drawn the background
            <View
                onStartShouldSetResponder={() => true}
                style={styles.container}
            > // The view to drawn your modal
            // Your content
            </View>
        </Androw>
    </View>
</TouchableWithoutFeedback>

我使用 TouchableWithoutFeedback,因为我不想在单击它时更改背景颜色。 我还在模态视图上添加了 onStartShouldSetResponder 以防止在视图内部单击时关闭模态。

我也没有使用 Modal 组件,因为我使用 react-navigation 完成了它。

<Modal isVisible={this.state.isVisible}
onBackdropPress={() => this.setState({ isVisible: false })}>
<View style={{ flex: 1 }}>
<Text>I am the modal content!</Text>
</View>
</Modal>
        <Modal
            animationType="slide"
            closeOnClick={true}
            transparent={true}
            visible={this.state.modalVisible}
            >
            <TouchableOpacity onPress={() => { this.setModalVisible(!this.state.modalVisible)}} style={{flex:1, justifyContent:'center', alignItems:'center',}}>
                <View style={{flex:0.2,backgroundColor:'white', margin:20, borderRadius:20, borderWidth:2, borderColor:'gray'}}>
                    <Text style={{margin:20}}>모달 테스트</Text>
                </View>
            </TouchableOpacity>
        </Modal>

这段代码是我的解决方案。

如果您使用的是expo ,则使用简单代码的简单解决方案。
这是一个完整的组件,您只需复制和粘贴即可使其正常工作。

//MyModal.js

import React from 'react';
import { BlurView } from 'expo-blur';
import { View, StyleSheet, Modal, TouchableWithoutFeedback } from 'react-native';

export const MyModal = ({ children, visible, onRequestClose, onPressOverlay, }) => {
  return (
     <Modal
      visible={visible}
      transparent
      animationType='none'
      onRequestClose={onRequestClose}
     >
       <TouchableWithoutFeedback onPress={onPressOverlay}>
         <BlurView
           style={{ ...StyleSheet.absoluteFill }}
           tint='dark'
           intensity={100}
         />
       </TouchableWithoutFeedback>
       <View style={styles.container}>
         {children}
       </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

现在您可以将其导入您的工作空间并像这样使用它。
我正在使用功能组件useState挂钩来显示或隐藏modal

//yourScreen.js

import React, { useState } from 'react';
import { View, Button } from 'react-native';
import { MyModal } form './path/to/MyModal.js';

const YourScreen = () => {
  const [modalVisible, setModalVisible] = useState(false);
  return (
    <View style={{ flex:1 }}>
      <MyModal
        visible={modalVisible}
        onRequestClose={()=>{
          setModalVisible(false);
        }}
        onPressOverlay={()=>{
          setModalVisible(!modalVisible);
        }}
      >
        // your modal content goes here
      </MyModal>
      <Button
        title='Show Modal' 
        onPress={()=>{
          setModalVisible(!modalVisible);
        }}
      />
    </View>
  );
}

export default YourScreen;

这是我的解决方案,

import React from "react";
import {Modal, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, View} from "react-native";

// make sure the styles props is passed to the model and contains modalContainer, as well as the childrenContainer style objects.

export default class DismissibleModal extends React.Component {
    render() {
        return (
            <Modal
              animationType="slide"
              transparent={true}
              visible={this.props.visible}
              onRequestClose={() => {this.props.dismiss()}}>
              <TouchableOpacity
                style={Styles.modal}
                activeOpacity={1}
                onPressOut={() => {this.props.dismiss()}}>
                    <View style={[this.props.styles.modalContainer]}>
                        <TouchableWithoutFeedback>
                            <View style={[this.props.styles.childrenContainer]}>
                                {this.props.children}
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
              </TouchableOpacity>
        </Modal>
        )
    }

}



const Styles = StyleSheet.create({
    modal: {
        flex: 1,
        backgroundColor: 'transparent',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    modalView: {
        backgroundColor: "white",
        borderRadius: 10,
        padding: 20,
        paddingTop: 20,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 9,
        },
        shadowOpacity: 0.50,
        shadowRadius: 12.35,

        elevation: 19,
  },
});

@Gui Herzog的回答非常好,但是将TouchableOpacity作为父组件,它会在涉及到子组件时处理冲突。

TouchableOpacity内部拥有多个组件不是一个好习惯,否则TouchableOpacity父级内部的所有组件都将是可点击的,解决此问题的最佳方法是,使您的TouchableOpacity组件处于绝对位置,屏幕宽度和高度为 100%。

这是一些例子:Modal.js

export default function(props){
    const { width, height } = Dimensions.get('window');
    const hp = hp => (hp / 100) * height;
    const wp = wp => (wp / 100) * width;
    const size = size => Math.round((size / 100) * width);
    return (
        <KeyboardAvoidingView>
            <TouchableOpacity
                style={{ position: 'absolute', width: wp(100), height: hp(100) }}
                onPress={props.onTouchOutSide}
            />
            <ScrollView>
                {/*...child*/}
            </ScrollView>
        </KeyboardAvoidingView>
    )
}

没关系。

这是您只需复制和粘贴的最佳解决方案。 它肯定会起作用。

我也面临问题这是解决方案。

import React,{useState} from 'react';

import{Button,StyleSheet,View,TouchableOpacity,Modal} from 'react-native';

const App=()=>{
   const [show, setShow] = useState(false);
    return (
      <View>
        <TouchableOpacity style={{marginTop:200}}>
          <Button title='show' onPress={()=>setShow(!show)}/>
          </TouchableOpacity>   
            <Modal transparent={true} visible={show} animationType="slide">
            <TouchableOpacity activeOpacity={1} style={{backgroundColor:'#000000aa',flex:1}} onPress={()=>setShow(!show)}/>
            
            <View style={{backgroundColor:'#FFFFFF',flex: 1}}>
                <View >
                     <Button title='close' onPress={()=>setShow(!show)}/>
               </View>  
            </View>
        </Modal>
      </View>
    )};
export default App;

您也可以在此处查看另一个示例:
https://snack.expo.dev/@saurabh_chavan/model-with-border-radius

如果您使用的是mobxredux之类的store 解决方案,您可以简单地使用 store 上的标志来解决。

下面是父母的代码,

      <Modal
        animationType="fade"
        transparent={true}
        visible={uiControlStore.dialogVisible}
        onRequestClose={() => {
          uiControlStore.dialogVisible = false;
        }}
      >
        <View
          style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.6)' }}
          onTouchStart={() => {
            if (!uiControlStore.childClicked) uiControlStore.dialogVisible = false;
            uiControlStore.childClicked= false;
          }}
        >
          <YourCustomDialog />
        </View>
      </Modal>

下面是孩子的代码。 (使用 mobx)

const YourCustomDialog: React.FC = observer(() => {
  const { uiControlStore } = useStores();

  return (
    <View
      style={[styles.container, styles.border]}
      onTouchStart={() => {
        uiControlStore.childClicked= true;
      }}
    >
    ...
  )
}

我意识到我参加这个聚会已经很晚了。 但我只是偶然发现了这个线程,而 Gui Herzog 的答案正是我想要的。 如果您不想添加任何外部依赖项,那就是要走的路。 谢谢!

但是,我想在我的组件中包含一些可选的负/正操作按钮,并从 react-native-paper 中获取它们的材质样式。 那时我意识到 react-native-paper 可能也有模态。

这是他们的文档: https ://callstack.github.io/react-native-paper/modal.html
他们还有一个对话框组件https://callstack.github.io/react-native-paper/dialog.html

因此,我最终使用了纸质对话框,如果您要在整个应用程序中使用该库,这是非常值得的。 默认情况下,Dialog 和 Modal 都处理点击外部的关闭。


这是在意识到 Dialog 组件已经存在之前创建的一个 Dialog 组件。

无论如何,我将把我在这里实现的内容留下,因为我认为它是一个很好的模板。

该组件在打字稿中。 确保更新@types/react-native否则您可能会看到一些“没有重载匹配此调用”错误。

import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {Button, Modal, Portal} from 'react-native-paper';

interface Action {
  action: () => void;
  text: string;
}

interface Props {
  closePressed: () => void;
  negativeAction?: Action;
  positiveAction?: Action;
  title?: string;
  text: string;
  visible: boolean;
}

export const Dialog: React.FC<Props> = ({
  closePressed,
  negativeAction,
  positiveAction,
  title,
  text,
  visible,
}) => {
  return (
    <Portal>
      <Modal
        visible={visible}
        onDismiss={closePressed}
        contentContainerStyle={styles.modalContainer}>
        <View style={styles.header}>
          {title && (
            <Text style={{fontWeight: 'bold', fontSize: 18, marginBottom: 10}}>
              {title}
            </Text>
          )}
          <Text style={styles.contentText}>{text}</Text>
        </View>
        <View style={styles.buttonContainer}>
          {negativeAction && (
            <Button mode="text" onPress={negativeAction.action}>
              {negativeAction.text}
            </Button>
          )}
          {positiveAction && (
            <Button mode="text" onPress={positiveAction.action}>
              {positiveAction.text}
            </Button>
          )}
        </View>
      </Modal>
    </Portal>
  );
};

const styles = StyleSheet.create({
  modalContainer: {
    borderRadius: 5,
    backgroundColor: 'white',
    padding: 10,
    margin: 20,
  },
  header: {padding: 20},
  contentText: {color: 'grey'},
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    paddingTop: 20,
  },
});

这是我完美的解决方案

模式代码:

const ListInModal = ({ showListModal, onClose, data, onSelectItem }) => {
  return (
    <Modal animationType="none" transparent={true} visible={showListModal} onRequestClose={() => onClose(false)}>
      <TouchableOpacity onPress={() => onClose(false)} style={styles.centeredView}>
        <View style={styles.modalView}>
          <ScrollView showsVerticalScrollIndicator={false}>
            {data.map((item, index) => (
              <>
                <TouchableOpacity
                  onPress={() => {
                    onSelectItem(item);
                    onClose(false);
                  }}
                  style={{ height: 43, justifyContent: 'center' }}
                >
                  <Text style={styles.itemLabel}>{item.label}</Text>
                </TouchableOpacity>
                {index <= data.length - 2 && (
                  <View
                    style={{
                      borderBottomColor: colors.white,
                      opacity: 0.2,
                      borderWidth: 1,
                      marginHorizontal: (24 / 375) * screenWidth,
                    }}
                  />
                )}
              </>
            ))}
          </ScrollView>
        </View>
      </TouchableOpacity>
    </Modal>
  );
};

造型:

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#00000099',
  },
  modalView: {
    marginHorizontal: wp('5%'),
    marginVertical: hp('10%'),
    backgroundColor: colors.popupBlack,
    borderRadius: 20,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  itemLabel: {
    fontSize: wp('5%'),
    color: colors.white,
    paddingHorizontal: (24 / 375) * screenWidth,
  },
});

用法:

<ListInModal
  data={projectState?.lvApplicationTypeList}
  showListModal={showListModal}
  onClose={(bool) => setshowListModal(bool)}
  onSelectItem={(item) => onPressApplicationType(item.label)}
/>

我是这样弄的。

<Modal
      visible={isVisible}
      onRequestClose={() => setIsVisible(false)}
      transparent={true}
      
      >
          <Pressable style={{
              flex:1,
              backgroundColor:'transparent',
            
          }}
          onPress={()=>setIsVisible(false)}
          />
          {/* Here comes your component*/}
    </Modal>

使用position:absoute absute 制作您的组件,以便Pressable可以覆盖整个背景。

@idiosync/react-native-modal 是一个基于钩子的模态系统。

https://www.npmjs.com/package/@idiosync/react-native-modal

您可以在配置对象中添加一个 onBackgroundPress 函数来实现您想要的:

useModal(
    {
      // all config params are optional apart from renderModal
      renderModal: () => <MyModal onClose={() => setModalIsVisible(false)} someProp={someProp} />,
      onBackgroundPress: () => setModalIsVisible(false),
      animationTypeIn: AnimationType.SLIDE_TOP,
    },
    modalIsVisible,
    [someProp] // dependencies array to trigger rerenders. Empty array is passed by default
  )

我尝试实现一些建议的答案,但是没有一个与模态内的按钮一起使用。

我在谷歌上搜索并发现不是使用TouchableWithoutFeedback ,而是名为Pressable的本机组件允许您检查单击的内容,因此仅在单击它而不是子组件时才允许您关闭。

return (
   <View>
      <Modal 
        animationType="slide"
        transparent={true}
        visible={visible}
        onRequestClose={() => {
           setVisible(false)}}
      >
        <Pressable
          onPress={(event) => event.target == event.currentTarget && setVisible(false)}
          style={styles.background}
        >
          <View style={styles.modal}>
             //Content of the modal
          </View>
        </Pressable>   
      </Modal> 
   </View>
)

这里找到了答案。

2022 答案 - 使用 React Native Hooks

通过单击 Overlay 来关闭 React Native Modal 最好使用 Pressable 按钮和 TouchableOpacity

下面的例子...

  • 从 react-native 导入 Pressable 和其他
import React, { useState } from 'react';
import {
  Pressable,
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Modal,
  TextInput,
  StyleSheet,
} from 'react-native';
  • 然后设置状态
const [modalVisible, setModalVisible] = useState(false);
  • 然后编写和设计你的模态
        <Modal
          animationType="slide"
          transparent={true}
          visible={modalVisible}
          onRequestClose={() => {
            setModalVisible(!modalVisible);
          }}
        >
          <TouchableOpacity
            onPress={() => setModalVisible(false)}
            style={styles.modalContainerStyle}
          >
            <Pressable
              onPress={() => setModalVisible(true)}
              style={styles.modalContent}
            >
              <ScrollView>
                <View>
                  <Text style={styles.modalTitle}>TITLE HERE</Text>

                  <Text style={styles.modalText}>
                    OTHER SMALLER TEXT HERE
                  </Text>

                  <Text style={styles.modalFormText}>AN INPUT</Text>
                  <TextInput
                    style={styles.modalInput}
                    value={inputValue}
                    onChangeText={(inputValue) => handleInputValue(inputValue)}
                    placeholder={'example@email.com'}
                  />

                  <View style={styles.btnView}>
                    <TouchableOpacity
                      onPress={() => setModalVisible(!modalVisible)}
                      underlayColor="white"
                    >
                      <View style={styles.buttonProceed}>
                        <Text style={styles.buttonText}>NEXT</Text>
                      </View>
                    </TouchableOpacity>
                  </View>
                </View>
              </ScrollView>
            </Pressable>
          </TouchableOpacity>
        </Modal>

  • 现在打开您的模式(使用文本按钮)
<Pressable onPress={() => setModalVisible(!modalVisible)}>
  <Text style={styles.openModal}>Open Modal</Text>
</Pressable>
  • 最后样式化你的模态
modalContainerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'flex-end',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  modalContent: {
    borderTopLeftRadius: 27,
    borderTopRightRadius: 27,
    width: '100%',
    height: '60%',
    backgroundColor: '#FFFFFF',
    paddingLeft: 33,
    paddingRight: 33,
    overflow: 'hidden',
  },
  modalTitle: {
    marginTop: 43,
    marginBottom: 14,
    fontSize: 19,
    lineHeight: 21,
    color: 'black',
    fontFamily: 'GraphikBold',
  },
  modalText: {
    fontSize: 15,
    lineHeight: 25,
    marginBottom: 38,
    color: 'black',
    fontFamily: 'GraphikRegular',
  },
  modalFormText: {
    marginBottom: 10,
    fontSize: 15,
    color: 'black',
    fontFamily: 'GraphikMedium',
  },
  modalInput: {
    marginBottom: 99,
    height: 44,
    paddingLeft: 17,
    paddingRight: 17,
    fontSize: 16,
    borderRadius: 10,
    marginBottom: 20,
    borderWidth: 1,
    fontFamily: 'GraphikRegular',
    borderColor: 'rgba(118, 118, 118, 0.17)',
  },
  openModal: {
    marginRight: 5,
    textAlign: 'right',
    color: '#ED2125',
    fontFamily: 'GraphikMedium',
  },

最近遇到了这个问题,尝试使用两个可触摸的不透明度来解决它,您还可以通过将 isDismissable 值传递给 false 来关闭点击任意位置行为的关闭。

import { View, Text, Modal, StyleSheet, TouchableOpacity } from 'react-native';
import React from 'react';

type PropType = {
  open: boolean;
  onClose: () => void;
  isDismissable?: boolean;
  children: JSX.Element | JSX.Element[];
};

const styles = StyleSheet.create({
  modalRootContainer: {
    flexGrow: 1,
  },
  outerContainer: {
    height: '100%',
  },
});

const BottomModal = ({
  open,
  onClose,
  isDismissable = true,
  children,
}: PropType) => {
  return (
    <Modal
      visible={open}
      transparent
      onRequestClose={onClose}
      animationType='slide'
    >
      <TouchableOpacity
        style={styles.outerContainer}
        activeOpacity={1}
        onPress={() => {
          if (isDismissable) onClose();
        }}
      >
        <View style={styles.modalRootContainer}>
          <TouchableOpacity activeOpacity={1}>{children}</TouchableOpacity>
        </View>
      </TouchableOpacity>
    </Modal>
  );
};

export default BottomModal;

使用 TouchableWithoutFeedback 和 react-native 的 Modal 最好和最简单的方法是

<Modal
  visible={visible}//modal visible true or false
  onRequestClose={()=>onClose(false)} // function to close modal
  transparent={true}
>
 <TouchableWithoutFeedback
   onPress={()=>onClose(false)}//outer button/view
   <View style={{flex:1, backgroundColor:'rgba(0,0,0,0.5)'}}>//for transparent view, this is outer view
    <TouchableWithoutFeedback>// outer button so any child view can be added
      <View>// this inner view
       <View>
       //your content goes here
       </View>
      </View>
    </TouchableWithoutFeedback>
   </View>
 </TouchableWithoutFeedback>
</Modal>

如果您想更好地添加平面列表以提供高度,这样内容就不会消失

*这是一个非常简单有效的解决方案,我只是将它应用到我的应用程序中,并按我的意愿工作。 只需将您的子组件包装到 TouchableOpacity

例子:

 <Modal
        animationType="slide"
        transparent={true}
        visible={IsCamaraShow}
        onRequestClose={() => {
          setIsCamaraShow(!IsCamaraShow);
        }}>
        <View style={Styles.centeredView1}>
        <TouchableOpacity style={Styles.centeredView1} 
        onPress={()=> setIsCamaraShow(!IsCamaraShow)}
        activeOpacity={1}
        >
          <View style={Styles.modalView1}>
           
            {cosnole.log( 'rest of your code') }
  
          </View>
        </TouchableOpacity>
        </View>
      </Modal>

会推荐以下对我有用的东西:

  • 在模式中使用两个<Pressable>组件
  • 第一个具有 opacity-1 和 flex-1,没有内容和关闭模态的onPress
  • 第二个样式根据您希望模态内容的显示方式和内部文本内容而定

 <Modal animationType="slide" transparent visible={isModalVisible} onRequestClose={() => setIsModalVisible(false) > <Pressable onPress={() => setIsModalVisible(false)} style={{flex: 1, opacity: 0}} /> <Pressable style{{height: '25%', width: '100%', position: 'absolute', bottom: 0, justify-content: 'center', align-items: 'center'}} > <Text>Content of modal</Text> </Pressable> </Modal>

我已经通过下面给出的代码在 react native 0.64 中解决了这个问题

 <Modal  
     isVisible={ModalVisible}  

      onBackdropPress={()=>{setModalVisible(false)}}
       >
      .
      .
      . 
  </Modal>

嗨,我正在使用轻量级弹出窗口react-native-easypopup ,当您点击弹出窗口时它也会自行关闭。

npm i react-native-easypopup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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