将宽度和高度设置为React Native模态窗口

63

我无法使用style属性来配置模态框的高度和宽度。是否有其他方法来设置模态框的高度和宽度?

 <Modal style={{height: 300, width: 300}}
        visible={this.state.isVisible}
        onRequestClose={this.closeModal}>
 </Modal>

上述代码不起作用。

5个回答

148
根据Modal文档,没有要设置的style属性。您可以尝试在<Modal>内部设置<View>尺寸。
<Modal transparent={true}
       visible={this.state.isVisible}
       onRequestClose={this.closeModal}>
  <View style={{
          flex: 1,
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center'}}>
    <View style={{
            width: 300,
            height: 300}}>
      ...
    </View>
  </View>
</Modal>

37
如果您希望模态框以独立的方框形式显示,并将底层视图“暗淡”,则需要在外部视图添加具有透明度的背景颜色 - 例如,backgroundColor:'#00000080'(50%不透明度的白色),并为内部视图添加纯色和填充,例如,backgroundColor:'#fff',padding:20 - Tim Scott
关于父元素的backgroundColor,'rgba(80,80,80,0.1)' 对我来说效果更好... - Yossi
1
不要忘记重新检查是否将“transparent”属性设置为true。 - kumar kundan
5
如果你想根据设备来调整模态框的大小:style={{width: Dimensions.get('window').width * 0.5, height: Dimensions.get('window').height * 0.5}} - panchicore
对我来说,在模态框的样式中添加margin: 0修复了这个问题... - Sathish Saminathan

12
尝试在 <Modal> 组件的样式中添加 margin:0

5
Modal文档中没有提到,但它有一个样式属性。
以下内容适用于我。
<Modal
    style={styles.modalContent}
    isVisible={this.state.isVisible}
    onBackdropPress={this.closeModal}
>
    <Component {...componentProps} />
</Modal>

const styles = StyleSheet.create({
    modalContent: {
        justifyContent: 'center',
        alignItems: 'center',
        margin: 0
    },
});

是的,它确实具有样式属性,但仍然无法将其居中对齐到屏幕中心。 - Ali Yar Khan
完全没有样式属性,请再次查看文档。 - Lonare

0

唯一解决它的方法是在 Modal 属性中传递 transparent={true}


这已经在被接受的答案中指明了,你能否添加更多细节到你的答案中,以便它可以独立出来? - Cristik

0
以下方法对我有效,经过尝试其他方法后,我不得不给模态框添加一些样式。
<Modal isVisible={this.state.isModalAddCompanionVisible} >
        <Button
        block
        style={{ marginTop: 20}}>
        <Text style={{ color: "white" }}  >Add Another Companion</Text>
      </Button>
       <View style={{backgroundColor: "white", height: 120}}> 
     
        </View>
      <View style={{flexDirection: 'row'}}>
      <Button
        block
        style={{ marginTop: 0,width: '40%'}}  onPress={this._toggleModalAddCompanion.bind(this)} >
        <Text style={{ color: "white" }} >Cancel</Text>
      </Button>
       <Button
        block
        style={{ marginTop: 0,width: '60%',}}   >
        <Text style={{ color: "white" }} >Add</Text>
      </Button>
     </View>
    </Modal>

虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题,将有助于提高您的帖子质量。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的答案以添加解释,并指出适用的限制和假设。 - Cristik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接