gpt4 book ai didi

reactjs - 如何在 React-Native 组件的警报中显示 {state}

转载 作者:行者123 更新时间:2023-12-03 14:31:27 25 4
gpt4 key购买 nike

我在测试时尝试提醒 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}
/>

现在的情况...每次更改输入文本时,您都会将文本设置为未定义。长话短说...您正在正确地尝试在警报中打印状态值...您只是没有正确设置状态值,因此它始终是未定义的。

关于reactjs - 如何在 React-Native 组件的警报中显示 {state},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172575/

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