В моем проекте React-Native я хочу использовать Modal внутри рендера. Я объявил одну переменную состояния, как показано ниже:
this.state = {
ModalVisibleStatus: false
};
Для показа Modal я объявил функцию-
ShowModalFunction(visible) {
this.setState({ModalVisibleStatus: visible});
}
И внутри функции рендеринга я только что написал, чтобы показать модальный режим, как показано ниже, на кнопке Press-
<Modal
transparent = {false}
animationType = {"slide"}
visible = {this.state.ModalVisibleStatus}
onRequestClose = { () => { this.ShowModalFunction(!this.state.ModalVisibleStatus)} } >
<View style = {{ flex:1, justifyContent: 'center', alignItems: 'center' }}>
<View style = {styles.ModalInsideView}>
{/* Put All Your Components Here, Which You Want To Show Inside The Modal. */}
<Text style = {styles.TextStyle}>Text Component With Some Sample Text In Modal. </Text>
<Button title = "Click Here To Hide Modal" onPress = {() => { this.ShowModalFunction(!this.state.ModalVisibleStatus)} } />
{/* Put All Your Components Here, Which You Want To Show Inside The Modal. */}
</View>
</View>
</Modal>
Теперь дело в том, что всякий раз, когда я запускаю экран, по умолчанию модальное окно остается открытым. Но я изначально объявил переменную ModalVisibleStatus ложной.
Вот весь код My Class-
HelloWorldApp.js
я
mport React, { Component } from 'react';
import {
Text, View, ScrollView, StyleSheet, Image, TextInput, NetInfo, TouchableOpacity,
TouchableHighlight, AsyncStorage, Modal, Alert, Button
} from 'react-native';
import { ICON_NOTE, ICON_TODO, ICON_TAG, ICON_REMINDER, ICON_URGENT, ICON_OFFICE, ICON_PERSONAL, ICON_WORK } from '../actions/ActionTypes';
import LoginScreen from '../components/LoginScreen';
export default class HelloWorldApp extends Component {
state = {
isLoading: false,
getValue: null,
ModalVisibleStatus: false
}
constructor() {
super();
this.state = {
title: '',
details: '',
timestamp: '',
status: '',
url: '',
mail: '',
phone: '',
category: '',
showLoader: false,
showAlert: false,
isNetConnected: true,
catImage: null,
}
};
updateImage(image, category) {
this.setState({
catImage: image,
category: category
})
}
updateValue(text, field) {
if (field == 'title') {
this.setState({
title: text
})
}
else if (field == 'details') {
this.setState({
details: text
})
}
}
ShowModalFunction(visible) {
this.setState({ ModalVisibleStatus: visible });
}
// net connection starts
async componentDidMount() {
const token = await AsyncStorage.getItem('token');
this.setState({ getValue: token });
}
render() {
console.info('#ZZZ2:', this.state.getValue);
return (
<View style = {{ flex: 1 }}>
<ScrollView keyboardShouldPersistTaps = {'handled'}>
<View style = {styles.container}>
<View style = {styles.inputContainerEmail}>
<Image style = {styles.inputIcon} source = {{ uri: this.state.catImage }} />
<TextInput style = {styles.inputs}
placeholder = "Title"
keyboardType = "email-address"
underlineColorAndroid='transparent'
onChangeText = {(text) => this.updateValue(text, 'title')} />
</View>
<View style = {styles.inputContainerDetails}>
<TextInput style = {styles.inputs}
placeholder = "Details"
multiline
underlineColorAndroid='transparent'
onChangeText = {(text) => this.updateValue(text, 'details')} />
</View>
<ScrollView horizontal = {true}>
<View style = {{ flexDirection: 'row', flex: 1, marginTop: 10, marginBottom: 10, marginRight: 20, marginLeft: 10 }}>
<TouchableOpacity style = {{ justifyContent: 'center', alignItems: 'center', marginRight: 10 }}
onPress = {() => { this.updateImage(ICON_NOTE, '1') }}>
<Image style = {styles.inputIconCategory} source = {{ uri: ICON_NOTE }} />
<Text style = {{ marginLeft: 25, marginTop: 5 }}>Note</Text>
</TouchableOpacity>
</View>
</ScrollView>
<TouchableOpacity style = {styles.buttonContainerRegister}
onPress = {() => {
console.info("#Ctegory:" + this.state.category + "\n Token:" + this.state.getValue + "\nTitle:" + this.state.title + "\nDetails:" + this.state.details + "\Timestamp:" + this.state.timestamp)
}}
>
<Text>Save</Text>
</TouchableOpacity>
<Modal
transparent = {false}
animationType = {"slide"}
visible = {this.state.ModalVisibleStatus}
onRequestClose = {() => { this.ShowModalFunction(!this.state.ModalVisibleStatus) }} >
<View style = {{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<View style = {styles.ModalInsideView}>
<Text style = {styles.TextStyle}>Text Component With Some Sample Text In Modal. </Text>
<Button title = "Click Here To Hide Modal" onPress = {() => { this.ShowModalFunction(!this.state.ModalVisibleStatus) }} />
{/* Put All Your Components Here, Which You Want To Show Inside The Modal. */}
</View>
</View>
</Modal>
<Button onPress = {() => { this.ShowModalFunction(true) }} title = "Click Here To Show Modal" />
</View>
</ScrollView>
</View>
);
}
}
Итак, я хочу, чтобы модальное окно закрывалось по умолчанию и открывалось, когда я нажимаю кнопку.
Это потому, что его значение становится неопределенным. Вам нужно определить все состояния в конструкторе.
isLoading:false,
getValue: null,
ModalVisibleStatus: false
вырежьте эти переменные из state = {...}
и поместите их внутрь this.state
в конструкторе.
Добавьте ModalVisibleStatus: false
в свой конструктор и вырежьте его из состояния
constructor() {
super();
this.state = {
title:'',
details:'',
timestamp : '',
status: '',
url:'',
mail:'',
phone:'',
category:'',
showLoader:false,
showAlert: false,
isNetConnected: true,
catImage: null,
ModalVisibleStatus: false
}
};
поместите ModalVisibleStatus: false в this.state, как это
this.state{
ModalVisibleStatus: false}
Я верю, что это сработает.
ShowModalFunction () {
this.setState({
ModalVisibleStatus: !this.state.ModalVisibleStatus
});
}