javascript - 为什么在 React-Native 中打开 Screen 时总是默认打开 Modal?

标签 javascript reactjs react-native

在我的 React-Native 项目中,我想在渲染中使用 Modal。我已经声明了一个状态变量,如下所示-

this.state = { 

        ModalVisibleStatus: false 
    };

为了显示 Modal,我声明了一个函数-

 ShowModalFunction(visible) {

    this.setState({ModalVisibleStatus: visible});

  }

在渲染函数中,我刚刚在按钮按下时编写了如下所示的显示模式-

 <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>

现在,问题是每当我默认启动 Screen 时,Modal 都会保持打开状态。但我最初已将变量 ModalVisibleStatus 声明为 false。

这是我的类(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.log('#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.log("#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 中。

关于javascript - 为什么在 React-Native 中打开 Screen 时总是默认打开 Modal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55585418/

相关文章:

javascript - 如何在nodejs中用koa获取 “HTTP_REFERER”?

javascript - eslint 强制执行一行操作/浪费变量?

html - ReactJS 如何手动触发点击事件?

reactjs - 用 React 测试

react-native - 在 React Native 中使用 ES6 的 getDefaultProps 函数相当于什么?

macos - 我可以在 docker 镜像中开发 react-native 应用吗

javascript - 对多个选项使用 Angular 指令

javascript - fabric.js fabric.Image.fromURL 在使用外部 url 时抛出错误

ReactJS:按钮启用禁用并更改颜色

android - 如何在 react 原生中解决(无法初始化类 org.codehaus.groovy.reflection.ReflectionCache)问题