react-native - 无法从 TextInput 获取值
问题描述
我目前在编辑页面代码中遇到了一个特定问题。问题如下:当用户想要编辑他们的用户名(在应用程序上)时,如果用户在 textInput 字段中键入(新)用户名(称为“名称”)并单击按钮(铅笔的图像按钮) ,应用程序不会更改用户名。在调试期间,调试器告诉我名称未定义。下面是代码片段:
edit(name) {
let { user } = this.state;
if (user) {
user.updateProfile({
displayName: name, // here i get the error of 'Undefied'
}).then(() => {
// Update successful.0
}).catch((error) => {
// An error happened.
});
}
}
下面是页面的完整代码:
//constructor
constructor() {
super();
this.state = {
user: {},
fetching: true,
}
this.onAuthStateChanged = this.onAuthStateChanged.bind(this);
}
componentDidMount() {
//Functionality
this.unsubscribeOnAuthChange = firebase.auth().onAuthStateChanged(this.onAuthStateChanged);
}
componentWillUnmount() {
this.unsubscribeOnAuthChange();
}
onAuthStateChanged(user) {
this.setState({ user, fetching: false })
}
edit(name) {
let { user } = this.state;
if (user) {
user.updateProfile({
displayName: name,
}).then(() => {
// Update successful.0
}).catch((error) => {
// An error happened.
});
}
}
ok = () => {
this.props.navigation.navigate('Home');
}
//Styles Account
render() {
let { user, fetching } = this.state;
if(fetching) return null;
return (
<ScrollView>
<View style={styles.container}>
<Text style={styles.text}>Account</Text>
<View style={styles.row}>
<Image source={require('./Picture/userImage1.png')} />
<TouchableOpacity onPress={() => this.edit(user.name)}>
<Image source={require('./Picture/pencil.png')} style={styles.pencil} />
</TouchableOpacity>
</View>
<Text style={styles.text1}>Welcome {user.displayName}</Text>
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(name) => this.setState({name})}
underlineColorAndroid='transparent'
autoCapitalize='none'
/>
<TouchableOpacity
style={styles.btn}
onPress={() => this.ok()}>
<Text style={{ fontSize: 17, color: '#fff' }}>Ok</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
谁能给我一些建议,说明为什么当用户单击图像按钮时出现“未定义”错误?
解决方案
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(name) => this.setState({name})} //<---Here you set value in state call `name`
underlineColorAndroid='transparent'
autoCapitalize='none'
/>
在这里,您正在传递对象键的值name
<TouchableOpacity onPress={() => this.edit(user.name)}>
只需简单地name
在 this.state 中定义 state 并this.state.name
在 edit 函数中传递 state 的值。
推荐阅读
- opengl - 协助翻译旋转的相机
- python - 如何解决''python35.dll' is not found''的问题?
- java - 使用 logback 和 nohup 在 Debian 后台运行 java 应用程序
- javascript - 使用 weather-js 模块返回意外的标识符错误
- c++ - 为什么即使我已经定义了“找不到匹配的重载”错误也会出现
- javascript - 如何使用 js-xlsx 编写带有图表的 excel 文件
- c++ - 真的有必要在这个指针上调用delete吗
- r - 如何在 R 中的 scatter3D 图的轴标签中包含下标
- go - 如何使用假客户端为客户端编写简单的测试?
- c - 我在制作从 DD.MM.YYYY 日期动态返回一年中日期的程序时遇到问题