请解释为什么这不起作用。我正在尝试在 React 中按下按钮时用另一个元素替换一个元素,并且根据所有文档,我正在做的事情应该有效。然而,React 完全忽略了状态变化并且拒绝重新渲染一个元素。这是我的文件:
import React, {Component} from 'react';
import {View, Text, TextInput, TouchableOpacity} from 'react-native';
import styles from '../styles';
import User from '../models/User';
export default class SignIn extends Component {
constructor(props){
super(props);
this.state = {
email: '',
password: '',
signIn: '',
errorMessage: null,
signUp: true
}
}
signIn(){
var err = e => this.setState({errorMessage: e.message});
var next = u => this.props.navigation.push('Details');
User.login(this.state.email, this.state.password, err, next);
}
signUp(){
var err = e => this.setState({errorMessage: e.message});
var next = _ => this.props.navigation.push('Details');
var user = new User(this.state.email, this.state.password);
user.save(err, next);
}
render(){
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{flexDirection: 'row', width: 300, justifyContent: 'center'}}>
<TouchableOpacity onPress={_ => this.setState({signUp: true})} style={[styles.navButton, styles.tabsButton]}>
<Text style={[styles.buttonText, styles.tabs]}>Sign Up</Text>
</TouchableOpacity>
<TouchableOpacity onPress={_ => this.setState({signUp: false})} style={[styles.grey, styles.tabsButton]}>
<Text style={[styles.greyText, styles.tabs]}>Sign In</Text>
</TouchableOpacity>
</View>
{this.state.signUp && <View>
<Text style={{color: 'red'}}>{this.state.errorMessage}</Text>
<TextInput
placeholder={'Email'}
style={styles.input}
value={this.state.email}
onChangeText={(email) => this.setState({email})}
/>
<TextInput
placeholder={'Password'}
style={styles.input}
secureTextEntry={true}
onChangeText={(password) => this.setState({password})}
/>
<TouchableOpacity style={styles.navButton}>
<Text style={styles.buttonText}>Sign Up</Text>
</TouchableOpacity>
</View>}
{!this.state.signUp && <View>
<Text style={{color: 'red'}}>{this.state.errorMessage}</Text>
<TextInput
placeholder={'Email'}
style={styles.input}
value={this.state.email}
onChangeText={(email) => this.setState({email})}
/>
<TextInput
placeholder={'Password'}
style={styles.input}
secureTextEntry={true}
onChangeText={(password) => this.setState({password})}
/>
<TouchableOpacity style={[styles.navButton]}>
<Text style={styles.buttonText}>Sign Up</Text>
</TouchableOpacity>
</View>}
</View>
)
}
}
顶部的登录按钮应该会改变状态并导致登录表单出现并且注册表单消失,而注册按钮应该做相反的事情。如果我console.log
改变后的状态,它已经改变了,但没有其他任何事情发生。到底是怎么回事?所有文档都表明您可以做到这一点,但它对我不起作用。我正在通过 Expo 在 Android 手机上运行该应用程序。