我在测试时尝试提醒我的 TextInput 组件的内容。代码位于下面的handleSubmit((函数中(第22行(。目前,警报弹出,但我得到的只是"标题",而this.state.text没有出现。我尝试了各种大括号,括号等。
请有人让我知道我做错了什么以及如何在警报中访问我的状态?将来会帮助我进行测试。我是 React Native 的新手,非常感谢对此的任何帮助。谢谢虚拟机!
import React, {Component} from 'react';
import {View, Text, TextInput, StyleSheet, TouchableOpacity, Alert} from 'react-native';
class GBTextInput extends Component {
constructor(props) {
super(props);
const {placeholder, text, label} = props;
this.state = {
text,
placeholder,
label
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({text});
}
handleSubmit(event) {
Alert.alert(
'Title'+this.state.text,
'I am a message'
);
event.preventDefault();
}
render() {
const {text, placeholder, label} = this.state;
const {containerStyle, labelStyle, inputStyle, buttonStyle} = styles;
return(
<View>
<View style={containerStyle}>
<View style={labelStyle}>
<Text>{label}</Text>
</View>
<TextInput
placeholder={placeholder}
style={inputStyle}
onChangeText={(text) => this.handleChange}
value={text}
onSubmitEditing={(text) => this.handleSubmit}
/>
</View>
<TouchableOpacity style={buttonStyle} onPress={this.handleSubmit}>
<Text>PRESS ME</Text>
</TouchableOpacity>
</View>
);
}
}
const styles= StyleSheet.create ({
containerStyle: {
flexDirection: 'row',
margin: 6
},
buttonStyle: {
alignSelf: 'stretch',
margin: 6,
padding: 6,
height: 40,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
borderColor: 'blue',
borderWidth: StyleSheet.hairlineWidth
},
labelStyle: {
height: 40,
width: '20%',
alignItems: 'flex-end',
justifyContent: 'center',
paddingRight: 6
},
inputStyle: {
height: 40,
width: '80%',
borderColor: 'gray',
borderRadius: 10,
borderWidth: StyleSheet.hairlineWidth,
position: 'relative',
paddingLeft: 6
},
});
export default GBTextInput;
我猜你的问题就在这里:
handleChange(event) {
this.setState({text});
}
应该是:
handleChange(text) {
this.setState({text});
}
您还需要将该值传递到 handleChange 函数中:
<TextInput
placeholder={placeholder}
style={inputStyle}
onChangeText={(text) => this.handleChange(text)}
value={text}
onSubmitEditing={(text) => this.handleSubmit}
/>
或
<TextInput
placeholder={placeholder}
style={inputStyle}
onChangeText={this.handleChange}
value={text}
onSubmitEditing={(text) => this.handleSubmit}
/>
现在的样子...每次更改输入文本时,您都将文本设置为未定义。长话短说...您正在正确尝试打印警报中的状态值...您只是没有正确设置状态值,因此它始终未定义。
这对我有用:
alert('Title ' + this.state.text);