注册用户的React Native TextInput为什么键入的文本没有显示或存储在setInput对象中



你好,我正在尝试导航,在React Native上创建一个文本输入,让用户输入他们的电子邮件密码和名称,并将其存储在对象中。但它并没有像我预期的那样发挥作用,我也不确定我哪里出了问题。我在网上看过类似的项目,但大多数项目都是使用React not React natie完成的,即使我尝试它们的实现,它仍然无法修复当用户按下注册按钮时文本不显示或允许存储的问题。

import { Text, View, TextInput, Button, StyleSheet} from 'react-native';
import {useState} from 'react';

export default function Home() {
const [input, setInput] = useState({
fullName:"",
email:"",
password: "",
});
const inputHandler = (e) => {
let name = e.target.fullName
let value = e.target.value;
setInput({
...input,
[name]: value,
});
};
const registerUser = (e) => {
e.preventDefault();
console.log(input)
setInput({
fullName:"",
email: "",
password:"",
});
};
return (
<View >
<Text style={styles.welcome}>
Welcome! Please Register Below
</Text>
<TextInput style={styles.input} placeholder="Name"  value={input.fullName} onChangeText={inputHandler}/>
<TextInput style={styles.input} placeholder="Email"  value={input.email} onChangeText={inputHandler}/>
<TextInput style={styles.input} placeholder="Password" value={input.password} onChangeText={inputHandler} />
<View style={styles.button}>
<Button title="Register" onPress={registerUser} />
</View>
<View style={styles.button}>
<Button title="Already Registered? Click here to login" onPress={()=> register()} />
</View>
</View>
);
}
const styles = StyleSheet.create({
welcome:{
padding:10
},
input: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
borderColor:'black',
borderWidth: 2,
margin:3
},
button:{
margin:5
}
});```
I have tried this.input.fullName in the value prop but that give me an error as that is not the way i defined it with my handlers. I also could go back to just using seperate states for each input like [name,setName] [password,setPassword] ect... but I would really like to understand where my knowledge is lacking for utilizing TextInput to pass user information and storing it.
From looking through similar stackoverflow questions I also tried changing my onChangeText to this
`onChangeText={(t) =>inputHandler(t)}`
but that also doesnt solve it
Thanks!

不显示文本,因为您对更改做出了反应,但没有正确更改状态。onTextChanges回调只返回text(作为字符串(,而不是Event。如果您需要跟踪Event,可以使用onChange回调。

但是,我建议你写你的逻辑尽可能干净和简单。首先,您应该将inputHandler分离为独立的文本更改函数,因为在您的情况下,它现在很容易管理。例如:

const onNameChanges = (text) => {
setInput(prev => ({
...prev,
fullName: text
}))
}

然后将其分配给TextInput的道具

<TextInput style={styles.input} placeholder="Name"  value={input.fullName} onChangeText={onNameChanges}/>

就是这样。您的代码按预期工作。我在这里为你准备了工作榜样https://snack.expo.dev/BkQi-kXr-8

最新更新