reactjs - 单击按钮后显示输入字段 react-native
问题描述
我正在学习 react-native,我想做一些简单的事情,用户可以输入一些信息,如姓名或其他信息,然后当他/她点击按钮时,它会在屏幕上显示你好,某某。我将onChangeText
设置设置state
为用户传递的内容,但它没有更新。同样单击该按钮不显示任何内容。我将在下面粘贴我的代码。任何帮助或建议。
app.js
import { Button } from "react-native";
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
Alert,
TextInput
} from "react-native";
const instructions = Platform.select({
ios: "Press Cmd+R to reload,\n" + "Cmd+D or shake for dev menu",
android:
"Double tap R on your keyboard to reload,\n" +
"Shake or press menu button for dev menu"
});
type Props = {};
export default class App extends Component<Props> {
constructor() {
super();
this.state = {
text: "Hello "
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = typedText => {
this.setState({
text: typedText
});
console.log(text);
};
render() {
return (
<View style={styles.container}>
<Text>{this.state.value}</Text>
<Button onPress={this.handleChange} title="Click Me " />
<TextInput
placeholder="Type your name here"
onChangeText={typedText => {
this.setState({
text: typedText
});
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10
},
instructions: {
textAlign: "center",
color: "#333333",
marginBottom: 5
}
});
解决方案
您也在 handlechange (onpress 函数)中设置状态,这根本不需要。您的 onPress 中不会有文本参数,您正在重置状态中的文本值。并且 handleChange 中的文本将是未定义的,因为您没有在任何地方设置它。
代码应该如下所示。
export default class App extends Component {
constructor() {
super();
this.state = {
text: "Hello "
};
this.handleChange = this.handleChange.bind(this);
}
onPress = () => {
console.log("current ==> ", this.state);
alert(this.state.text);
};
handleChange = typedText => {
console.log("update => ", typedText);
this.setState(
{
text: typedText
}
);
};
render() {
return (
<View style={styles.container}>
<Text>{this.state.value}</Text>
<Button onPress={this.onPress} title="Click Me " />
<TextInput
placeholder="Type your name here"
onChangeText={this.handleChange}
/>
</View>
);
}
}
推荐阅读
- html - 即使在静音和遵守不同的浏览器规则后,自动播放也不适用于 html 视频
- perl - perl中拆分语法中缺少表达式
- python - 如何将实例绑定描述符作为引用参数传递给函数?
- xcode - 如何在不使用 Xcode 的情况下导出 Apple Developer Id 证书
- java - Java cucumber IllegalArgumentException 路径不一致
- php - 表查询,从table1中选择数据,但前提是table2中的用户设置设置为特定值
- javascript - 从胡须模板 Moodle 3.7 中获取数据
- internationalization - 全球分数的 PageSpeed Insights
- python - NameError:未定义名称“board1”
- vba - 为整个word文档应用pagesetup