class LoginComponent extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
}
onLogin() {
const { email, password } = this.state;
alert(email);
}
renderInput = (
placeholder: string,
type: string,
name: string,
value: string
): Object => (
<Input
placeholder={placeholder}
type={type}
name={name}
value={this.state[name] || value}
onChangeText={({target}) => this.setState({[name]: target.value})}
/>
);
render() {
return (
...
{this.renderInput(
"Email Address",
"emailAddress",
"email"
)}
...
<TouchableOpacity onPress={this.onLogin}>
<Text>Submit</Text>
</TouchableOpacity>
)
}
}
当我单击“提交”时,会发生错误
答案 0 :(得分:0)
您需要绑定方法,否则this
没有作用域。在您的构造函数中添加:
this.onLogin = this.onLogin.bind(this)
答案 1 :(得分:0)
您需要将this
绑定到onLogin
函数。
简单的方法是使用arrow
函数,
onLogin = () => { //Auto binds `this`
const { email, password } = this.state;
alert(email);
}
或者您可以使用constructor
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.onLogin = this.onLogin.bind(this)
}
注意:
您的renderInput
函数带有4个参数,
renderInput = (
placeholder: string,
type: string,
name: string,
value: string
): Object => (
但是您只传递了3个参数,
{this.renderInput(
"Email Address", //This is placeholder
"emailAddress", //This is type
"email" //This is name
)}
这里type
= emailAddress
,我们没有emailAddress
作为类型,它应该仅为email
。
您可以像这样简化输入,
<Input
placeholder={placeholder}
type={type}
name={name}
value={this.state[name] || value}
onChangeText={(text) => this.setState({[name]: text})}
/>