gpt4 book ai didi

typescript - React Native TypeScript TextInput 不工作

转载 作者:行者123 更新时间:2023-12-04 17:35:45 25 4
gpt4 key购买 nike

我正在尝试通过做一个基本的应用程序来学习 React Native。我遵循了许多在线教程,并为登录屏幕创建了以下类:

import React, { Component } from "react";
import { View, StyleSheet, TextInput, Button, Alert, TouchableHighlight, Text } from "react-native";
import { styles } from "../styles/CommonStyles";

class LoginScreen extends Component {
constructor(props: Readonly<{}>) {
super(props)
}
state = {
email: ''
}
static navigationOptions = {
title: 'Login',
header: null
}
render() {
const { navigate } = this.props.navigation
return (
<View style={styles.container}>

<TextInput
style={loginStyles.emailInput}
multiline={false}
autoCorrect={false}
autoCapitalize='none'
keyboardType='email-address'
value={this.state.email}
onChangeText={(text) => this.handleEmail(text)}
placeholder='Enter Email'/>

<TouchableHighlight
style={loginStyles.buttonGenerateOTP}
onPress={this.onGenerateOTP}>
<Text
style={loginStyles.textGenerateOTP}>GENERATE OTP</Text>
</TouchableHighlight>
</View>
)
}

handleEmail(text: string) {
console.log('Email: ' + text)
this.setState({ email: text })
console.log('State Email: ' + this.state.email)
}

onGenerateOTP() {
Alert.alert(
'Email Entered',
this.state.email,
[
{ text: 'OK', style: 'cancel' }
],
{ cancelable: false }
)
}
}

export default LoginScreen

const loginStyles = StyleSheet.create({
emailInput: {
fontSize: 15,
backgroundColor: '#ECECEC',
borderColor: '#999999',
borderRadius: 4,
borderWidth: 0.5,
alignSelf: 'stretch',
textAlign: 'center',
margin: 10,
},
buttonGenerateOTP: {
backgroundColor: '#008CBA',
borderRadius: 4,
alignSelf: 'stretch',
justifyContent: 'center',
alignItems: 'center',
margin: 10,
padding: 10,
},
textGenerateOTP: {
fontSize: 20,
color: '#FFFFFF',
},
})

它只包含一个输入和一个按钮,在输入的电子邮件上应显示警报。但是当我点击按钮时,出现以下错误:

undefined is not an object (evaluating 'this.state.email')
onGenerateOTP
LoginScreen.tsx:43:8
...

我对 react native 和 typescript 还很陌生,但是查看代码,我找不到任何问题。我在这里做错了什么?

编辑handleEmail(text) 函数中的登录实际上是在打印状态,虽然使用以前的文本值(即,当我输入 QWERT 时,它会打印 QWER ,当我输入 QWERTY 时,它会打印 QWERT),但文本参数记录正确

最佳答案

我解决了这个问题。问题是我必须绑定(bind)功能。按照下面更改构造函数解决了这个问题。

constructor(props: Readonly<{}>) {
super(props)
this.handleEmail = this.handleEmail.bind(this)
this.onGenerateOTP = this.onGenerateOTP.bind(this)
}

关于typescript - React Native TypeScript TextInput 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713639/

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