【发布时间】:2019-02-09 20:35:40
【问题描述】:
我在测试时试图提醒我的 TextInput 组件的内容。代码在下面的 handleSubmit() 函数中(第 22 行)。目前,警报弹出,但我得到的只是“标题”,而 this.state.text 没有出现。各种花括号、方括号等我都试过了。
请有人告诉我我做错了什么以及如何在警报中访问我的状态?将来会帮助我进行测试。我是 React Native 的新手,非常感谢在这方面的任何帮助。谢谢vm!
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;
【问题讨论】:
-
想想如何设置状态
onChangeText。您是否正确处理text?你打电话给event listener正确吗? -
感谢 wlh - 发现问题了! :)
标签: reactjs react-native state alert textinput