首页 > 解决方案 > 模态不使用道具关闭

问题描述

不知道为什么,但是从另一个函数访问该方法时模式没有关闭。我可以在组件中控制台记录该方法,但该方法不起作用。

这是 closeModal() 函数所在的主要 ReviewScreen.js

import React, {Component} from 'react';
import {Modal} from 'react-native';
import {TouchableOpacity} from 'react-native';
import {View, Text, StyleSheet} from 'react-native';
import ReviewsModal from '../components/ReviewsModal';

class ReviewsScreen extends React.Component {
  state = {
    isModalVisible: false,
  };

  toggleModal() {
    this.setState({isModalVisible: !this.state.isModalVisible});
  }

  render() {
    return (
      <View style={{flex: 1}}>
        <Modal
          animationType="slide"
          visible={this.state.isModalVisible}
          onRequestClose={() => this.toggleModal()}>
          <View style={{flex: 1}}>
            <ReviewsModal closeModal={() => this.toggleModal()} />
          </View>
        </Modal>
        <View>
          <TouchableOpacity onPress={() => this.toggleModal()}>
            <Text> click me </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

export default ReviewsScreen;

这是我尝试运行该功能的组件 ReviewsModal.js

import React from 'react';
import {KeyboardAvoidingView} from 'react-native';
import {View, Text, StyleSheet} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import Icon from 'react-native-vector-icons/MaterialIcons';
import colours from '../constants/colours';

export default class ReviewsModal extends React.Component {
  render() {
    return (
      <KeyboardAvoidingView styles={styles.container} behaviour="padding">
        <TouchableOpacity
          style={{position: 'absolute', top: 64, right: 32}}
          onPress={this.props.closeModal}>
          <Icon name="close" size={24} color={colours.dark} />
        </TouchableOpacity>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

标签: javascriptreact-native

解决方案


您可能需要绑定您的函数以获得正确的上下文。在您的 ReviewScreen 构造函数中添加:

constructor(props) {
     super(props)

     this.state = {
         isModalVisible: false
     }

    
     this.toggleModal = this.toggleModal.bind(this)
 }

推荐阅读