gpt4 book ai didi

javascript - react native 模态始终可见

转载 作者:行者123 更新时间:2023-11-30 08:18:52 28 4
gpt4 key购买 nike

我尝试在 React Native 中点击按钮时显示模态。最初模态状态是隐藏的,点击按钮模态应该显示。

但现在每次都可见。

//Login.tsx

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, Button, TouchableOpacity, ScrollView } from 'react-native';
import axios from 'axios';
import InvalidUserModal from '../Modal/InvalidUser';

export default class LoginFirst extends Component {
constructor(props) {
super(props);

this.state = {
modalVisible: false
};
}

triggerModal() {
this.setState(prevState => {
return {
modalVisible: true
}
});
}

render() {
return (
<View style={styles.container}>
<Button
onPress = {() => this.triggerModal()}
title = "Open Modal"
color = "orange">
</Button>
<InvalidUserModal
image = '../../../../assets/user.png'
data = 'Krunal'
display = { this.state.modalVisible }
/>
</View>
);
}
}

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

模态内容

import React, { Component } from 'react';
import { Modal, View, Image, Text, StyleSheet } from 'react-native';

const InvalidUser = (props) => (
<View>
<Modal
visible={props.display}
animationType={'slide'}
onRequestClose={() => console.log('closed')}
>
<View>
<Image
source={props.image}
style={styles.image}
/>
<Text style={ styles.text}>
{props.data}
</Text>
</View>
</Modal>
</View>
);

const styles = StyleSheet.create({
image: {
marginTop: 20,
marginLeft: 90,
height: 200,
width: 200
},
text: {
fontSize: 20,
marginLeft: 150
}
});

export default InvalidUser;

上面的代码运行良好。唯一的问题是模态总是显示。从不隐藏。请查看下面的屏幕。

App screen

代码中还有什么需要做的吗。真的卡在这里了。

最佳答案

我不确定这是否有效,但这里有一些您应该尝试的方法。

Modal 中移除 View

const InvalidUser = (props) => (
{// <View> removed }
<Modal
visible={props.display}
animationType="slide" {// you don't need {} if it's a string}
onRequestClose={() => console.log('closed')}
>
<View>
<Image
source={props.image}
style={styles.image}
/>
<Text style={ styles.text}>
{props.data}
</Text>
</View>
</Modal>
{// </View> removed }
);

setState 更好的方式

如果只想将状态设置为true,则不需要知道prevState

// inside triggerModal 
this.setState({modalVisible: true});

对类属性使用箭头函数,避免多次渲染箭头函数。

// arrow function
triggerModal = () => {
this.setState({modalVisible: true});
}

render() {
return (
<View style={styles.container}>
<Button
{// avoid creating a new function on every render }
onPress = {this.triggerModal}
title = "Open Modal"
color = "orange">
</Button>
<InvalidUserModal
image = '../../../../assets/user.png'
data = 'Krunal'
display = { this.state.modalVisible }
/>
</View>
);
}
}

关于javascript - react native 模态始终可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57277470/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com