javascript - 模态不使用道具关闭
问题描述
不知道为什么,但是从另一个函数访问该方法时模式没有关闭。我可以在组件中控制台记录该方法,但该方法不起作用。
这是 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',
},
});
解决方案
您可能需要绑定您的函数以获得正确的上下文。在您的 ReviewScreen 构造函数中添加:
constructor(props) {
super(props)
this.state = {
isModalVisible: false
}
this.toggleModal = this.toggleModal.bind(this)
}
推荐阅读
- scala - Spark scala - sql插入操作后的输出行数
- javascript - 如何更新 TypeScript 的版本?
- neo4j - Cypher - 数字有序关系
- java - Java Delete files older than N days with Path, Filename and N days as variable
- php - Symfony3 存储库方法不起作用
- mongodb - Customize existing document and add new fields in mongo aggregation
- javascript - 需要验证出生日期用户应该是 18 岁及以上
- c# - 不动态更新系统托盘通知图标?
- python - 如何将.condarc中提供的代理用于environment.yml中的pip包?
- python - GMM 函数的 GaussianMixture 等效项(sklearn python)