[英]How do I close a React Native Modal?
我目前遇到一個問題,我可以很好地打開我的本機反應模式,但是一旦打開,我似乎無法關閉它。 我大約三周前才開始使用react-native,所以我對此非常陌生。
我嘗試過實施在網上找到的解決方案,但似乎沒有任何效果。 打開功能很棒,並且似乎運行得很好,但是在關閉模式時,我嘗試過的所有事情似乎都沒有賦予模式這種能力。 我無法在任何地方為我的確切問題找到可靠的解決方案!
這就是我打開模態的方式。
constructor(props) {
super(props);
this.state = {
refreshing: false,
display: false
};
}
triggerModal() {
this.setState(prevState => {
return {
display: true
}
});
}
<View>
<Button onPress = { () => this.triggerModal() } title = "Open Modal"></Button>
<DisplayModal display = { this.state.display } />
</View>
這是模態本身,我正在嘗試使用按鈕將其關閉。
import React from 'react'
import { Modal, View, Image, Text, StyleSheet, Button } from 'react-native';
const DisplayModal = (props) => (
<Modal visible={ props.display } animationType = "slide"
onRequestClose={ this.display }>
<View>
<Button title="close" onPress = { () => !props.display }></Button>
</View>
</Modal>
)
export default DisplayModal;
由於我對react-native的了解是有限的,因此很難圍繞框架函數的某些方面進行思考……我可能只是在代碼中的某個地方犯了一個愚蠢的錯誤。
感謝您提供有關此問題的幫助!
您幾乎已經掌握了它,但是我們可以做一些調整以使其按需工作。
由於DisplayModal
沒有自己的狀態,因此該狀態必須由其父組件控制。 因此,考慮到這一點,我們可以執行以下操作。 首先,將另一個名為closeDisplay
道具closeDisplay
給DisplayModal
。 我們將傳遞一個將state
的display
屬性設置為false
的函數。
<DisplayModal
display={this.state.display}
closeDisplay={() => this.setState({display: false})} // <- we are passing this function
/>
然后,在DisplayModal
組件中,我們將調用該函數以關閉模式。 因此,您的DisplayModal
組件應如下所示:
const DisplayModal = (props) => (
<Modal
visible={ props.display }
animationType = "slide"
onRequestClose={ this.display }>
<View>
<Button
title="close"
onPress = { () => props.closeDisplay() }> // <- here we call the function that we passed
</Button>
</View>
</Modal>
)
請注意, DisplayModal
組件中Button
的onPress
函數被稱為函數closeDisplay()
。 然后,此函數在父組件中設置狀態,然后將其向下傳遞回DisplayModal
組件,使其隱藏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.