如何在屏幕中央将React Native Modal显示为小窗口

时间:2020-03-05 19:07:22

标签: react-native react-native-stylesheet

即使已完成样式设置,我也想在屏幕中间显示我的本机模式,但窗口会出现在屏幕顶部,而不是屏幕中央。 到目前为止,这是我尝试过的:

 <Modal animationType = {"slide"} transparent = {true}
        style={styles.modal}
               visible = {this.state.modalVisible}
               onRequestClose = {this.closeModal}>

               <View style={{justifyContent: 'center', backgroundColor: '#ffff', margin: 0, 
          alignItems: 'center'}}>
                  <Text >Enter Email</Text>
                  <TextInput
              underlineColorAndroid='transparent'
              onChangeText={(email) => this.setState({email})}/>
              <Text>Enter Password</Text>
              <TextInput 
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(password) => this.setState({password})}/>
                  <TouchableHighlight onPress = {() => {
                     this.toggleModal(!this.state.modalVisible)}}>
                     <Text >Close</Text>
                  </TouchableHighlight>
               </View>
            </Modal>

这是模态样式:

const styles = StyleSheet.create({
      modal:{
          position:"relative",
        width: 250, 
        height: 100,
        backgroundColor: '#FFF',
        justifyContent: 'center',
        alignSelf: 'center',
      }
});

1 个答案:

答案 0 :(得分:4)

ReactNative本机style中没有Modal道具(请参考this link上的文档,有关更多信息,请参见答案的后面)。

要正确设置Modal的样式,您需要创建一个View样式的flex: 1作为所有子元素的父元素。例如,您将执行以下操作:

<Modal
  animationType={"slide"}
  transparent={true}
  visible={this.state.modalVisible}
  onRequestClose={this.closeModal}
>
  <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> // modalContainerStyle
    <View style={styles.childStyle}>
       {...}
    </View>
  </View>
</Modal>

其中childStyle是示例中模态中第一个元素的样式。

您还可以在上面的代码中将backgroundColor中的rgba(0,0,0,0.5)添加到modalContainerStyle中,以使其具有适当的模态外观。

回到style道具,它仅在称为react-native-modal的RN Modal的社区管理包装中提供。您可以在这里了解更多信息:https://github.com/react-native-community/react-native-modal