javascript - React Native Button onPress 不起作用
问题描述
按钮 onPress 不起作用,方法 onButtonPress() 根本没有被调用。我不确定我做错了什么。
我有一个未打印的 console.log 语句。顺便说一下,下面的代码来自 Stephen Grider 的 react native udemy 课程
下面是 loginForm.js 的代码
任何帮助将不胜感激。
import React, { Component } from 'react';
import { Text } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection, Input, Spinner, Field } from './common';
class LoginForm extends Component {
state = { email: '', password: '', error: '', loading: false };
onButtonPress() {
const { email, password } = this.state;
console.log('da');
this.setState({ error: '', loading: true });
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}
onLoginFail() {
this.setState({
error: 'Authentication Failed',
loading: false
});
}
onLoginSuccess() {
this.setState({
email: '',
password: '',
loading: false,
error: ''
});
}
renderButton() {
if (this.state.loading) {
return <Spinner size="small" />;
}
return <Button onPress={this.onButtonPress.bind(this)}>Log in</Button>;
}
render() {
return (
<Card>
<CardSection>
<Field
placeholder="user@gmail.com"
label="Email"
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Field
secureTextEntry
placeholder="password"
label="Password"
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</CardSection>
<Text style={styles.errorTextStyle}>{this.state.error}</Text>
<CardSection>{this.renderButton()}</CardSection>
</Card>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 20,
alignSelf: 'center',
color: 'red'
}
};
export default LoginForm;
解决方案
你需要绑定this
到renderButton
,你可以使用自动绑定的箭头函数this
,
renderButton = () => { //Arrow function binds this automatically
if (this.state.loading) {
return <Spinner size="small" />;
}
return <Button onPress={this.onButtonPress.bind(this)}>Log in</Button>;
}
推荐阅读
- mysql - 从相似的行MYSQL中选择一行
- java - 引导层初始化期间发生错误。plexus.container.default:无效的模块名称:'default' 不是 Java 标识符
- python - 如何使用按钮将图像加载到 kivy 窗口中?
- r - R - 在 plot_ly 中结合 tidy eval 和 tilde 时出错
- python - 如何修复“参数未填充”错误?
- javascript - 反应JS中的打字稿
- angular - 当用户选择多个“x”选项时禁用未选择的选项
- flutter - 在“有效飞镖”之后捕获错误和异常的正确方法是什么?
- electron - 在windows上创建APPX包和DMG包
- javascript - 使用 CSS 调整图像大小时如何解决模糊图像问题?