Jit*_*ese 6 javascript react-native
我试图在 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'
}
});
Run Code Online (Sandbox Code Playgroud)
模态内容
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;
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常。唯一的问题是模态总是显示。从不隐藏。请看下面的屏幕。
代码中还有什么要做的吗。真的卡在这里了。
我不确定这是否有效,但这里有一些你应该尝试的事情。
ViewModalconst 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 }
);
Run Code Online (Sandbox Code Playgroud)
setState以更好的方式如果您只想将状态设置为true,则不需要知道prevState。
// inside triggerModal
this.setState({modalVisible: true});
Run Code Online (Sandbox Code Playgroud)
// 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6299 次 |
| 最近记录: |