我是React Native的新手并且不熟悉js。
当我按下TextInput
(Button
下面Text
时,我希望程序显示我在Button
中写的内容。我想也许我应该做两个状态:把state1 text
作为Text
输入,把state2 mimin
作为TextInput
输入,当Button pressed
时,把state2 mimin
到state1 text
。
我已尝试使用下面的代码,但当我点击Button
时,它给了我红页。
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
TextInput,
Alert,
View
} from 'react-native';
export default class Hella extends Component {
constructor(props) {
super(props);
this.state = {text: '', mimin: ''};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(mimin) => this.setState({mimin})}
/>
<Button
onPress={onButtonPress}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
<Text style={styles.instructions}>
{this.state.text}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
}
});
const onButtonPress = () => {
Hella.setState({
text: Hella.state.mimin -------> where the error happened
});
};
AppRegistry.registerComponent('Hella', () => Hella);
错误是
undefined is not an object (evaluating 'Hella.state.mimin')
onButtonPress
<project location>/index.android.js:61
我做错了什么?我该如何申报?我在哪里可以了解更多信息?
答案 0 :(得分:9)
您的onButtonPress
应该在class
内,因为您想setState
export default class Hella extends Component {
constructor(props) {
...
}
onButtonPress = () => {
this.setState({
text: this.state.mimin
});
}
render() {
return (
...
<Button
onPress={this.onButtonPress}
...
/>
...
);
}
}
React Native使用了很多React概念。学习React的基础知识将为您提供很多帮助https://facebook.github.io/react/tutorial/tutorial.html
答案 1 :(得分:0)
函数定义应如下所示。
onButtonPress = () => {
this.setState({
text: this.state.mimin
});
}